PHP fopen 相对路径失效 - 神秘问题

3
我知道“一定有什么东西被改变了”,但我的代码似乎突然之间出了问题。
我的服务器目录结构大致如下:
/ /scripts /audit /other_things
我在“scripts”文件夹中有一个脚本(假设它叫做“/scripts/MyScript.php”),它使用curl从网页中获取数据,并在“audit”文件夹中保存一个日期的网页副本。
为了写入audit文件夹,我使用了以下代码: $fh = fopen("./audit/2008-09-09-183000.backup.log","w");
然而,它停止工作并抛出以下错误:
[function.fopen]:failed to open stream:No such file or directory in /home/web/website.co.uk/audit/2008-09-09-183000.backup.log on line 353
不过,我已经通过将路径更改为“../audit/2008等。”来解决了这个问题(这是两个点号,而不是一个)。
逻辑推断出,在服务器配置中一定发生了某些变化,但是是什么呢?这是我管理的专用服务器。我该如何避免再次发生这样的情况?
我甚至已经查看了MyScript.php的SVN,并且所有以前的版本都使用了单个点号的路径。
3个回答

8
使用dirname(__FILE__)获取当前文件的文件系统路径,然后从那里使用相对路径定位您的audit目录。
例如,在scripts/MyScript.php中,dirname(__FILE__)将返回/home/web/website.co.uk/scripts。您可以可靠地将/../audit附加到其中。
(请注意,即使在includerequire的文件中也适用于此情况,此时它将返回所包含的文件所在的目录)。

0

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

这可能是由于访问脚本时使用的路径导致的,例如,如果您之前访问 http://website.co.uk/MyScript.php 由于某些URL重写或其他原因,现在正在访问 http://website.co.uk/scripts/MyScript.php

我记得还有其他可能的罪魁祸首,但我现在想不起来了。您是否修改了一些重写规则或URL?(例如,开始使用PATH_INFO?)


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>';
    };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接