检查文件时出现语法问题

sar*_*012 -1 php

这段代码之前已经有效,但是我把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="" />';
        }
        ?>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我正在检查一个文件,如果存在,显示它,如果没有,则显示一个占位符.

$ _SESSION ['id']变量确实存在,并且正在脚本中的其他位置使用.

有什么想法是什么问题?

谢谢

Fel*_*ing 5

好吧,让我们简单一点:

你有你的图像

/foo/bar/images/users/*.jpg
Run Code Online (Sandbox Code Playgroud)

你的脚本在

/foo/bar/script.php
Run Code Online (Sandbox Code Playgroud)

之前,哪个有效,因为realpath(dirname(__FILE__) . $user_image)创造了

/foo/bar/image/users/*.jpg
Run Code Online (Sandbox Code Playgroud)

但是现在,当您将脚本移动到同一级别(/foo/baz/script.php)上的另一个目录时,前一个命令的输出将是

 /foo/baz/image/users/*.jpg
Run Code Online (Sandbox Code Playgroud)

并且此路径存在.

您在评论中说过,您将脚本移动到另一个目录.如果您也没有移动图像,那么您的脚本肯定会失败.


另请注意,通过URL(即从外部)或通过文件路径(即从内部)访问图像存在差异.您的图像将始终可用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
Run Code Online (Sandbox Code Playgroud)

更新:

如果您的脚本比图像低一级,则修复可能是:

file_exists(realpath(dirname(__FILE__) . '/../' . $_SESSION['id'] . 'a.jpg'))
Run Code Online (Sandbox Code Playgroud)

这会产生类似的东西/foo/images/users/v3/../12a.jpg...意味着上升到一个水平.

或者上升几个级别并使用$user_image:

realpath(dirname(__FILE__) . '/../../..' . $user_image)
Run Code Online (Sandbox Code Playgroud)