0
votes

I see why this below is bad and that htmlspecialchars must be used to prevent some xss vulnerabilities:

<?php $url = '<plaintext>';
echo $url;?>

like so:

<?php $url = '<plaintext>';
htmlspecialchars($url, ENT_QUOTES, "UTF-8");
echo $url;?>

In my database i store the filename only which is user provided. (im sure this will change as i learn more about this subject)

What im wondering though, is if this below is actually doing anything to protect against XSS? Is it less of a vulnerability compared to the previous case?

I've tried injecting script tags with and without htmlspecialchars and it seems to do nothing in either case. The script code wont execute.

Is it secure? Is htmlspecialchars the right tool for the job? How can i make it better?

$sql['image'] is fetched from my database and this below is the code that displays the image.

<?php $url = "/images/" . $sql['image'] . ".jpg";
$url = htmlspecialchars($url, ENT_QUOTES, "UTF-8");?>
<img src="<?php echo $url;?>">

outputs:

<img src="/images/test.jpg">
1

1 Answers

1
votes

In principle you can't trust any user input, ever. If $sql['image'] will directly or indirectly be provided by users, then it won't matter if you add constants to the beginning and end of that string. Either way you'll have to rely on htmlspecialchars() not containing any bugs that would allow scripting to be injected.

To actually increase security in this case, you'd have to take somewhat more drastic measures. One popular method for that would be to simply assign file names yourself, for example by hashing on the contents of the file and using that hash instead of the original file name to store the file. md5() and sha1() tend to come in handy for that.

Also, assuming the users provide the images whose file names you're storing, you'd have to make sure those can't be used to get the job done, either. For example, the users might upload an SVG with an embedded script instead of a JPEG, thus potentially completely avoiding any validation or mangling on the file name itself.