Reputation: 5747
I have a piece of code that checks whether an image exists in the file system and if so, displays it.
if (file_exists(realpath(dirname(__FILE__) . $user_image))) {
echo '<img src="'.$user_image.'" />';
}
else {
echo "no image set";
}
If I echo $user_image
out, copy and paste the link into the browser, the image is there.
However, here, the 'no image set' is always being reached.
The $user_image
contents are http://localhost:8888/mvc/images/users/1.jpg
Some of these functions not needed?
Any ideas? Broken code or a better way of doing it (that works!)?
Upvotes: 1
Views: 287
Reputation: 2499
Beside @hek2mgl answer which i think is correct, i also think you should switch to is_file()
instead of file_exists()
.
Also, you can go a bit further like:
if(is_file(dirname(__FILE__). '/' . $user_image) && false !== @getimagesize(dirname(__FILE__) . '/'. $user_image)) {
// image is fine
} else {
// it isn't
}
L.E:1
Oh great, now you are telling us what $user_image contains? Couldn't you do it from the start, could you?
So you will have to:
$userImagePath = parse_url($user_image, PHP_URL_PATH);
$fullPath = dirname(__FILE__) . ' / ' . $userImagePath;
if($userImagePath && is_file($fullPath) && false !== @getimagesize($fullPath)) {
// is valid
}else {
// it isn't
}
L.E: 2
Also, storing the entire url is not a good practice, what happens when you switch domain names? Try to store only the relative path, like /blah/images/image.png
instead of http://locathost/blah/images/image.png
Upvotes: 2