【问题标题】:How to create and write a file in a specific directory in PHP? [duplicate]如何在 PHP 中的特定目录中创建和写入文件? [复制]
【发布时间】:2018-08-09 06:58:14
【问题描述】:

我想在特定目录中创建一个文件 failure-log.log 并写入它。已经从数据库中获得了目录路径。路径是这样的:

D:/folder-one/folder-two/

我的 PHP 代码正在另一个目录中执行,如下所示:

C:/apache24/crawler/admin/startService.php

如何创建文件并写入文件?

【问题讨论】:

  • 我注意到您想在 Web 根目录之外编写一个文件,出于安全考虑,不建议这样做。如果您坚持,您必须关闭safe_mode 或在php.ini 中将doc_root 留空。即使您执行了上述操作,您仍然需要给予适当的许可。
  • @Raptor 感谢您让我意识到这一点

标签: php file


【解决方案1】:

首先使该文件夹位置对 Web 服务器可写。然后使用下面的代码在该位置创建文件。

$myfile = fopen("D:/folder-one/folder-two/file.log", "a") or die("Unable to open location for log file !");
$txt = "Log details goes here ...";
fwrite($myfile, $txt);
fclose($myfile);

【讨论】:

    【解决方案2】:

    确保你使用绝对路径(你也可以在相对路径上使用 realpath() 来确定路径)并且目录是可写的

    然后

    $dir = 'your/path';
    
    file_put_contents($dir ."/failure-log.log", $contentOfFile);
    

    如果你不希望每次都删除文件的内容,那么我建议使用 FILE_APPEND

    file_put_contents($dir ."/failure-log.log", $contentOfFile, FILE_APPEND);
    

    【讨论】:

      【解决方案3】:

      使用file_put_contents 方法,像这样:

      $file ="D:/folder-one/folder-two/";
      $current = file_get_contents($file); 
      $current .= 'yourcontenthere';
      file_put_contents($file, $current);
      

      你可以发送标志到file_put_contents,比如FILE_APPEND

      $file ="D:/folder-one/folder-two/"; 
      $text = 'yourcontenthere';
      file_put_contents($file, $text, FILE_APPEND);
      

      在这种情况下,您不必检索旧内容,您可以在上面的链接中检查和其他标志。

      在此之前检查文件是否存在也是个好主意。

      【讨论】:

      • 看看FILE_APPEND in file_put_contents()
      • @NigelRen 已编辑 :) 谢谢!
      • 不推荐使用大文件。该函数会将文件复制到内存中,以便将文件复制到新位置,这可能会达到 PHP 的最大内存限制。
      【解决方案4】:
      1. 写入文件

        $writeFile = @fopen('/path/to/save/file', 'w+'); @fwrite($writeFile, $content); @fclose($writeFile);

      与:

      w+: will create a new file if it does not exist and overwrite if it exists
      a: append to file already exist
      a+: append to file already exist and create a new file if it does not exist
      
      1. 如果你从数据库中加载路径目录,你可能需要创建多目录

        if( !is_dir($path) ) { mkdir($path, 0777, true); }

      与:

      $path: path you were loaded from db
      

      【讨论】:

      • 永远不要将777权限分配给任何文件夹或文件;这是一个常见的错误,会导致安全问题。如果你想创建一个对脚本有写权限的文件夹,你可以使用 should 775 来代替。
      • 你为什么不给我投票? @猛禽
      • 上一条评论中提到过。
      • @Raptor 我正在使用窗口操作系统,实际上,我不在乎您的“导致安全问题”,因为模式权限在 Window 上不起作用。另外,mkdir 默认的模式权限是 0777。你可以在这里查看php.net/manual/en/function.mkdir.php
      猜你喜欢
      • 2013-04-15
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多