Is it safe to display a image using $_GET for path? For example using this format: image.php?path=/images/example.jpg
Asked
Active
Viewed 416 times
0
-
at least urlencode() the path and image name, the whitespaces and other characters can mess things up in some browsers – aleation Apr 30 '13 at 10:47
-
`image.php?path=/../../../../etc/passwd` may be a problem if the php script just blindly processes the path. – Joachim Isaksson Apr 30 '13 at 10:48
-
then for url I could use image.php?path=example.jpg and on php script I can do this: $image = "/images/".$_GET["path"]; – morandi3 Apr 30 '13 at 10:50
-
2@morandi3 which in my example would turn into `$image="/images//../../../../etc/passwd` and possibly send the password file. – Joachim Isaksson Apr 30 '13 at 10:53
-
hmm, yes, you are right – morandi3 Apr 30 '13 at 10:55
-
2A solution would be to define an array on php code with allowed values. – morandi3 Apr 30 '13 at 10:57
-
1Rule #1: **Don't trust user input**. – HamZa Apr 30 '13 at 14:03
3 Answers
2
Yes you can, just make sure you use isset
so that it doesn't throw undefined index if someone fiddles with your URL, also you need to check whether the path is valid else show some other image, like image not found by writing text in alt
attribute
if(isset($_GET['index'])) {
echo '';
}
Points to be looked for:-
- Anybody can tinker URL
- You'll have to sanitize the value
- Often path's will be changed so be sure you use
alt
text if image is not found - If you don't sanitize, will lead to easy intrusion for hackers
Inshort I suggest you NOT TO DO SO

Mr. Alien
- 153,751
- 34
- 298
- 278
2
Its perfectly safe if you check the path exists after using basename($_GET['path'])
on the file name, also define your path to the images folder.
Then check that it is an image with getimagesize($path)
. If any fail, change the filename to a not found image or such.
<?php
$path_to_images = '/images/';
$not_found_img = './path/to/not_found_image.jpg';
// check path is set and not empty
if(empty($_GET['path'])){
$path = $not_found_img;
}else{
$path = $path_to_images.basename($_GET['path']);
// check that image exists
if(!file_exists($path)){
$path = $not_found_img;
}else{
//Check if image
if($img_size = getimagesize($path)) {
//alls good $path validated
}else{
$path = $not_found_img;
}
}
}
// do somthing with your $path
?>

Lawrence Cherone
- 46,049
- 7
- 62
- 106
0
Completely yes. There are no problems, hackers can't give there bad code, what can hack your page or work with your database. But take care on some other elements.

Matej Kolec'ko
- 119
- 7
-
Luckily, [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) [only](http://stackoverflow.com/questions/2526522/csrf-cross-site-request-forgery-attack-example-and-prevention-in-php) affects visitors :) – thaJeztah May 01 '13 at 07:34