Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中创建和写入特定目录中的文件?_Php_File - Fatal编程技术网

如何在PHP中创建和写入特定目录中的文件?

如何在PHP中创建和写入特定目录中的文件?,php,file,Php,File,我想在特定目录中创建一个文件failure-log.log并写入它。已从数据库中获取目录路径。路径如下所示: D:/folder-one/folder-two/ 我的PHP代码在另一个目录中执行,如下所示: C:/apache24/crawler/admin/startService.php $file ="D:/folder-one/folder-two/"; $current = file_get_contents($file); $current .= 'yourcontenther

我想在特定目录中创建一个文件failure-log.log并写入它。已从数据库中获取目录路径。路径如下所示:

D:/folder-one/folder-two/
我的PHP代码在另一个目录中执行,如下所示:

C:/apache24/crawler/admin/startService.php
$file ="D:/folder-one/folder-two/";
$current = file_get_contents($file); 
$current .= 'yourcontenthere';
file_put_contents($file, $current);
如何创建文件并写入?

使用如下方法:

C:/apache24/crawler/admin/startService.php
$file ="D:/folder-one/folder-two/";
$current = file_get_contents($file); 
$current .= 'yourcontenthere';
file_put_contents($file, $current);
您可以将标志发送到
文件\U put\U contents
,如
文件\U APPEND

$file ="D:/folder-one/folder-two/"; 
$text = 'yourcontenthere';
file_put_contents($file, $text, FILE_APPEND);
在这种情况下,您将不必检索旧内容,您可以在上面的链接中检查和其他标志


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

首先使该文件夹位置可供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);

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

然后

如果您不希望每次都删除文件的内容,那么我建议使用file\u APPEND

file_put_contents($dir ."/failure-log.log", $contentOfFile, FILE_APPEND);
  • 写入文件

    $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
    
  • 如果从数据库加载路径目录,可能需要创建多个目录

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

  • 与:


    查看
    FILE\u APPEND
    中的
    FILE\u put\u contents()
    @NigelRen edited:)谢谢!不建议使用大文件。该函数将文件复制到内存中,以便将文件复制到新位置,这可能会达到PHP的最大内存限制。我注意到您希望在web根目录外编写文件,出于安全考虑,不建议这样做。如果您坚持,则必须在php.ini中关闭或保留为空。即使您执行了上述操作,您仍然需要给予适当的权限。@Raptor感谢您让我意识到这一点。切勿将777权限分配给任何文件夹或文件;这是一个常见的错误,会导致安全问题。如果你想创建一个对脚本有写权限的文件夹,你应该使用775。你为什么要否决我@Raptor在前面的评论中提到过。@Raptor我使用的是Windows操作系统,实际上,我不在乎你的“导致安全问题”,因为模式权限在Windows上不起作用。另外,mkdir默认模式权限为0777。你可以在这里查一下。