Php创建一个文件,如果不存在

shy*_*ick 14 php file-handling

我尝试创建文件并动态编写内容.以下是我的代码.

$sites = realpath(dirname(__FILE__)).'/';
$newfile = $sites.$filnme_epub.".js";

if (file_exists($newfile)) {
    $fh = fopen($newfile, 'a');
    fwrite($fh, 'd');
} else {
    echo "sfaf";
    $fh = fopen($newfile, 'wb');
    fwrite($fh, 'd');
}

fclose($fh);
chmod($newfile, 0777);

// echo (is_writable($filnme_epub.".js")) ? 'writable' : 'not writable';
echo (is_readable($filnme_epub.".js")) ? 'readable' : 'not readable';
die;
Run Code Online (Sandbox Code Playgroud)

但是,它不会创建文件.

请分享您的答案和帮助.谢谢!

Ale*_*ván 20

尝试使用:

$fh = fopen($newfile, 'w') or die("Can't create file");
Run Code Online (Sandbox Code Playgroud)

用于测试是否可以在那里创建文件.

如果您无法创建该文件,那可能是因为该目录不是Web服务器用户可写的(通常是"www"或类似的).

chmod 777 folder对要创建文件的文件夹执行a操作,然后重试.

它有用吗?

  • 永远不要只将文件夹或文件权限设置为777.有关详细信息,请参阅[this post](http://superuser.com/a/273533/157802). (4认同)
  • 再次阅读答案。我没有说任何关于根文件夹的事情。假设您有一个像“bob”这样的用户名。Web 服务器以完全不同的用户身份运行(假设为“www”)。“www”不能写入“bob”的文件夹,除非: 1)“www”被添加到“bob”的组中,并且该文件夹至少有 775 权限。2) 将文件夹的所有者从“bob”更改为“www”(使用“chown”)。3)该文件夹可由任何用户写入(它有777权限,您可以使用“chmod”更改它们)。 (3认同)

小智 8

要确保文件存在,然后再对其进行任何操作,您只需触摸它:

if (!file_exists('somefile.txt')) {
    touch('somefile.txt');
}
Run Code Online (Sandbox Code Playgroud)

这只会创建一个以当前时间为创建时间的空文件。与 fopen 相比的优势在于您不必关闭文件。

如果需要,您还可以设置创建时间。以下代码将创建一个创建时间为昨天的文件:

if (!file_exists('somefile.txt')) {
    touch('somefile.txt', strtotime('-1 days'));
}
Run Code Online (Sandbox Code Playgroud)

但是:如果您对已经存在的文件使用 touch,您应该关心文件的修改时间将被更改的事实。


Cyb*_*org 7

使用该功能is_file检查文件是否存在。

如果文件不存在,此示例将创建一个新文件并添加一些内容:

<?php

$file = 'test.txt';

if(!is_file($file)){
    $contents = 'This is a test!';           // Some simple example content.
    file_put_contents($file, $contents);     // Save our content to the file.
}

?>
Run Code Online (Sandbox Code Playgroud)