php检查file_exists()从第三级到根目录

时间:2014-07-11 16:21:09

标签: php

我为此奋斗,有什么建议吗?

  SERVER HTTPDOCS DIR
        /images         <--MAINDOMAIN - domain.com
        /m              <--SUBDOMAIN  (Third level) ROOT DIR  OF m.domain.com

    *FROM m.domain.com/test.php*

$dir="../images";   //Trying to read outside the subdomain root dir

if (is_dir($dir)) {
      $oggetto = @opendir($dir);
      while (false !== ($files = @readdir($oggetto))) {
             if($files != "." && $files != "..") {//print filename}

它无法识别目录。

1 个答案:

答案 0 :(得分:0)

来自is_dir()的PHP文档,关于第一个传递的参数:

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.

换句话说,如果指定相对路径,则会将其视为相对于当前正在执行的脚本,这就是您的脚本在第一种情况下工作但在第二种情况下不工作的原因。我个人在操作文件和目录时更愿意使用完整路径,以确保我知道我指向的是什么。稍微探讨一下,看看我在说什么,试试这个:

<?php
$current_dir = dirname(__FILE__);
$path = realpath( $current_dir . '/../images' );

var_dump( $path );

通常,PHP框架倾向于在引导期间指定一些完整路径,例如文档根目录的绝对路径,应用程序文件夹,日志文件夹等,然后在指定文件路径时使用这些路径。这很方便,并且往往非常稳定,因为引导程序文件往往保留在同一文件路径中,而当您遇到问题时,当您将脚本从一个文件夹移动到另一个文件夹时,路径解析会中断。我说这一切都是为了说你可以考虑创建一个&#34;文件根&#34;例如,头文件中的变量包含每个脚本中的头文件,然后在需要创建文件路径时使用该变量。