【问题标题】:php fopen relative path broken - mysteryphp fopen 相对路径损坏 - 神秘
【发布时间】:2010-11-21 03:38:43
【问题描述】:

我知道“必须更改某些内容”,但我的代码似乎无缘无故地在一夜之间崩溃了。

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

/
/脚本
/审计
/other_things

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

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

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

然而,它停止工作,抛出

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

不过,我已经通过将路径更改为

来解决这个问题

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

逻辑表明服务器配置中一定发生了一些变化,但是什么?这是我管理的专用服务器。我怎样才能避免类似的事情再次发生?

我什至已经通过 SVN for MyScript.php 并且所有以前的版本都使用了单个 .在路径中。

【问题讨论】:

    标签: php relative-path path


    【解决方案1】:

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

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

    (请注意,这甚至适用于included 或required 文件——在这种情况下,它将返回包含文件所在的目录)。

    【讨论】:

      【解决方案2】:

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

      这可能是由于用于访问脚本的路径而发生的,例如,如果您在 http://website.co.uk/MyScript.php 之前由于某些 url 重写或诸如此类的原因而现在正在访问 http://website.co.uk/scripts/MyScript.php

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多