如果不存在,则使用PHP脚本创建文件


PHP script to create file if no exist

我的php代码有一个小问题。请查看:

<?php
$urlud = $json['url'];
$content = 'Content 1 if file no exist will generate';
$filename = $json['id'].".html";
if (file_exists($filename)) {
    echo "File exists!";
} else {
    file_put_contents('dir1/'. $filename, $content, FILE_APPEND | LOCK_EX);
}
?>
<?php
$urlud = $json['url'];
$content = 'Content 2 if file no exist will generate';
$filename = $json['id'].".html";
if (file_exists($filename)) {
    echo "File exists!";
} else {
    file_put_contents('dir2/'. $filename, $content, FILE_APPEND | LOCK_EX);
}
?>

这段代码将在不同的目录中生成2个具有不同内容的文件。我的问题是:

  1. 这段代码不断替换我的旧文件内容。有没有办法让它只在文件不存在的情况下才创建?
  2. 有没有其他的输入,使这段代码更简单?

谢谢。

if (file_exists('dir1/'. $filename))

if (file_exists('dir2/'. $filename))

您必须检查文件的完整路径,而不仅仅是文件名。例如,假设$filename为"readme.txt"这个文件可能不存在于你的脚本路径中。你希望它在dir1或dir2