【问题标题】:PHP create file in same directory as scriptPHP在与脚本相同的目录中创建文件
【发布时间】:2018-07-05 13:44:20
【问题描述】:
$content = "some text here"; 
$fp = fopen("myText.txt","w"); 
fwrite($fp,$content); 
fclose($fp);

上面的代码在 PHP 脚本所在的文件夹中创建了一个文件。但是,当 Cpanel Cron 调用脚本时,会在主目录中创建文件。

我希望在 php 脚本所在的同一文件夹中创建文件,即使它由 cron 运行。

怎么做?

【问题讨论】:

  • 您应该在 PHP 代码中使用文件夹的完整路径
  • 尝试__DIR__ constant 访问当前脚本目录或basename( __FILE__),如果你正在运行旧的PHP解释器

标签: php cron cpanel


【解决方案1】:

尝试使用__DIR__ . "/myText.txt" 作为文件名。
http://php.net/manual/en/language.constants.predefined.php

【讨论】:

    【解决方案2】:

    使用dirname(__FILE__) 内置宏尝试类似的操作。

    <?php
    
    $content = "some text here";
    $this_directory = dirname(__FILE__);
    $fp = fopen($this_directory . "/myText.txt", "w");
    fwrite($fp, $content); 
    fclose($fp);
    
    ?>
    

    __FILE__ 是当前运行的 PHP 脚本的完整路径。 dirname() 返回给定文件的包含目录。因此,如果您的脚本位于 /mysite.com/home/dir/prog.phpdirname(__FILE__) 将返回...

    /mysite.com/home/dir
    

    因此,fopen 语句中的附加“./myText.txt”。我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 2010-12-29
      • 2016-07-18
      • 2018-06-16
      • 1970-01-01
      • 2018-09-28
      相关资源
      最近更新 更多