I was wondering how I can make a really simple GET and echo request more secure

The code:

$src = $_GET['src']; 
echo "<img src='$src' />";

Basically, I have a URL like example.com/link.php?src=imgname.jpg

Theoretically, I think it's possible to exploit it by inserting external URL's and trying to get them parsed on the site. Would you recommend doing a preg_match to only allow images and remove URLS?


You have implemented a Cross Site Scripting (XSS) vulnerability. This type of injection vulnerability can be used by an attacker to steal the credentials of your users, or make users perform actions on your site or against other sites without their knowledge. For more information about XSS see wikipedia: http://en.wikipedia.org/wiki/Cross-site_scripting

Your vulnerability could be expoited by somebody using a src parameter that closes img tag and then inserts javascript into the page. Something like:

'/><script>alert('hello world')</script>

So YES, you should validate your input. Match it against a regular expression using preg_match such as


You should also escape strings that are outputted to html using the htmlspecialchars function in php.

$src = htmlspecialchars($src, ENT_QUOTES);
echo "<img src='$src' />";
  • Validation is only part of the story. The much bigger issue here is the lack of proper encoding for an attribute. Although, in this particular case, regular expressions do okay, the idea doesn't generalise well. – Brendon Feb 9 '13 at 20:32
  • Good point, I added that advice to the answer. – Stephen Ostermiller Feb 9 '13 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.