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

时间:2013-12-14 05:30:51

标签: 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;

但是,它不会创建文件。

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

3 个答案:

答案 0 :(得分:17)

尝试使用:

$fh = fopen($newfile, 'w') or die("Can't create file");

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

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

对要创建文件的文件夹执行chmod 777 folder,然后重试。

有效吗?

答案 1 :(得分:4)

要确保在执行任何操作之前文件存在,您可以触摸该文件:

if (!file_exists('somefile.txt')) {
    touch('somefile.txt');
}

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

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

if (!file_exists('somefile.txt')) {
    touch('somefile.txt', strtotime('-1 days'));
}

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

答案 2 :(得分:2)

使用功能 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.
}

?>
相关问题