简体   繁体   English

检查文件时的语法问题

[英]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! 这段代码以前可以运行,但是我将C&P放到了一个新的地方,由于某种原因,现在不起作用了!

        <?
        $user_image = '/images/users/' . $_SESSION['id'] . 'a.jpg';
        if (file_exists(realpath(dirname(__FILE__) . $user_image))) 
        {
            echo '<img src="'.$user_image.'" alt="" />';
        } 
        else 
        {
            echo '<img 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. $ _SESSION ['id']变量确实存在,并且正在脚本中的其他地方使用。

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 之前,这有效,因为realpath(dirname(__FILE__) . $user_image)创建

/foo/bar/image/users/*.jpg

But now, when you eg moved your script to another directory on the same level ( /foo/baz/script.php ), the output of the previous command will be 但是现在,当您将脚本移动到同一级别的另一个目录( /foo/baz/script.php )时,上/foo/baz/script.php命令的输出将为

 /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 (ie from the outside) or via a file path (ie from the inside). 另请注意,通过URL(即从外部)或通过文件路径(即从内部)访问图像存在差异。 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 : 您的图像始终可以通过www.yourdomain.com/images/users ,但是如果将PHP脚本移至另一个目录,则dirname(__FILE__) 必须提供另一个值,因此测试将失败

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 . 这将生成类似/foo/images/users/v3/../12a.jpg .. means going up a level. ..表示要提高水平。

Or going up several levels and using $user_image : 或者上升几个级别并使用$user_image

realpath(dirname(__FILE__) . '/../../..' . $user_image)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM