When is the htmlspecialchars() to be used exactly?
I know that laravel {{}} is automatically escaping, but I have a case where I don't know how to implement {{}} - see "view" example, so I would go instead for htmlspecialchars() . As far as I know it should be used each time I output info previously stored in DB, but in my case I also have pictures, which are stored in a folder on the server. Once the user tries to upload picture(s) he receives error messages(in red <div>
) with the name of the successfully/unsuccessfully uploaded picture. Does that need to be escaped to? I dont know whether the view info should be escaped. So that the error messages could still remain red, I decided to use htmlspecialchars() in the controller, which I suppose is terribly wrong?
Controller
if (......)
{
$msgs[] = '<div style="color:red">Could not upload: ' . htmlspecialchars($_FILES['image']['name'][$key]) . ' - picture size should be less than 10MB, in the following formats: jpg, jpeg, gif, png, bmp.</div>';
}
else
{
$fileToMove = $_FILES["image"]["tmp_name"][$key];
$newFileLoc = 'images' . DIRECTORY_SEPARATOR . time() . $_FILES['image']['name'][$key];
move_uploaded_file($fileToMove, $newFileLoc);
$msgs[] = '<div>Picture ' . htmlspecialchars($_FILES['image']['name'][$key]) . ' has been successfully uploaded to the gallery!</div>';
}
}
Internally, when you use {{ }}
in blade syntax, I believe it calls the e()
method. So instead of using htmlspecialchars($someString)
, you should use e($someString)
.
You should use this any time you are putting data onto your page which has previously been submitted by the user to your system.