php fopen相对路径破碎 - 神秘

时间:2009-08-19 23:38:35

标签: php relative-path path

我知道“必须改变一些东西”,但我的代码似乎已经无缘无故地破坏了一夜。

我的服务器目录结构是这样的:

  

/    
/脚本    
/审计    
/ other_things

我在“scripts”文件夹中有一个脚本(假设它叫做“/scripts/MyScript.php”),该文件夹使用curl从网页收集数据,并保存在“审计”中读取的网页的日期副本“文件夹。

要写入审计文件夹,我使用了

  

$ fh = fopen(“./ audit / 2008-09-09-183000.backup.log”,“w”);

然而,停止工作,投掷

  

[function.fopen]:无法打开流:第353行/home/web/website.co.uk/audit/2008-09-09-183000.backup.log中没有此类文件或目录

然而,我已经通过改变

的路径来解决这个问题
  

“../ audit / 2008 etc.”来自“./audit/2008”(即两个句号/句号,而不是一个)

逻辑规定服务器配置中必须更改某些内容,但是什么?它是我管理的专用服务器。我怎样才能避免这样的事情再次发生?

我甚至通过SVN for MyScript.php,所有以前的版本都使用过单曲。在路上。

3 个答案:

答案 0 :(得分:7)

使用dirname(__FILE__)获取当前文件的文件系统路径。然后使用相对路径找到您的audit目录。

例如,在scripts/MyScript.php内,dirname(__FILE__)将返回/home/web/website.co.uk/scripts。您可以可靠地将/../audit附加到该页面。

(请注意,这甚至适用于include d或require d文件 - 在这种情况下,它将返回包含文件所在的目录。)< / p>

答案 1 :(得分:0)

您的CWD(当前工作目录)已更改,它是文档根目录,现在是文档根目录/脚本。

由于用于访问脚本的路径,可能发生了这种情况,例如,如果您在http://website.co.uk/MyScript.php之前由于某些网址重写或其他原因而进行了操作,那么您现在正在访问http://website.co.uk/scripts/MyScript.php

我似乎记得还有其他可能的罪魁祸首,但我现在不记得了。你有没有改写一些重写规则或URL? (即,开始使用PATH_INFO?)

答案 2 :(得分:0)

确定这个答案为时已晚,我是一个学习者,也许可以帮助其他人!

    $dir=(__DIR__).'/'; //Path to current script location
    $path="../"; //Use any relative path to your script as you want and exists
    $file="file.txt"; //A dummy test file
    $fullpath=$dir.$path.$file; //That is the important path to store your file
    $content="This is a dummy text"; //As you read

    $draft=fopen($fullpath,"x") or die ('Something went wrong'); //"x" mean only for write if file already exists return error use any flag you need you can use any var name for "$draft" can use for example "$handle" instead
    fwrite($draft, $content); //Writes content inside file
    fclose($draft); //Close the dummy test file 

    if (file_exists($fullpath)) { //Verify is file has been created
      echo 'File created '."Ok!".'<br>'; 
    } else {
      echo 'File do not created function is '."scrubbed!".'<br>';
    };

    $data=file_get_contents($fullpath); //Verifies if content writed is ok

    if ($data==$content) {
      echo 'All content is '."Ok!".'<br>'; 
    } else {
      echo 'All content is '."scrubbed!".'<br>';
    };