Syntax problem when checking for a file
This piece of code has previously worked but I have C&P it to a new place and for some reason, it now won't work!
<?
$user_image = '/images/users/' . $_SESSION['id'] . 'a.jpg';
if (file_exists(realpath(dirname(__FILE__) . $user_image)))
{
echo '<img src="'.$user_image.'" alt="" />';
}
else
{
echo '<im开发者_如何学运维g src="/images/users/small.jpg" alt="" />';
}
?>
As you can see, I am checking for a file, if exists, showing it, if not, showing a placeholder.
The $_SESSION['id'] variable does exist and is being used elsewhere within the script.
Any ideas what the problem is?
Thanks
Ok lets put it simple:
You have your images at
/foo/bar/images/users/*.jpg
and your script was at
/foo/bar/script.php
before, which worked, because realpath(dirname(__FILE__) . $user_image)
creates
/foo/bar/image/users/*.jpg
But now, when you e.g. moved your script to another directory on the same level (/foo/baz/script.php
), the output of the previous command will be
/foo/baz/image/users/*.jpg
and this path does not exist.
You said in your comment you moved the script to another directory. If you didn't move the images too, your script definitely fails.
Also note there is a difference in accessing the images via a URL (i.e. from the outside) or via a file path (i.e. from the inside). Your images will always be available via www.yourdomain.com/images/users
, but if you move your PHP script into another directory, dirname(__FILE__)
has to give you another value and thus the test will fail:
foo/
|
- baz/
| |
| - script.php <-absolut path: /foo/baz/images/users/...
|
- bar/ <- entry point of URL is always here
|
- script.php <- absolut path: /foo/bar/images/users/...
- images/
|
- users/
|
- *.jpg
Update:
If your script is one level below the images, a fix could be:
file_exists(realpath(dirname(__FILE__) . '/../' . $_SESSION['id'] . 'a.jpg'))
This will generate something like /foo/images/users/v3/../12a.jpg
. ..
means going up a level.
Or going up several levels and using $user_image
:
realpath(dirname(__FILE__) . '/../../..' . $user_image)
精彩评论