如果不存在,php 创建一个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20580017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Php create a file if not exists
提问by shyamkarthick
I try to create files and write the contents dynamically. Below is my code.
我尝试创建文件并动态写入内容。下面是我的代码。
$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;
However, it does not create the files.
但是,它不会创建文件。
Please share your answers and help. Thanks!
请分享您的答案和帮助。谢谢!
回答by Alejandro Iván
Try using:
尝试使用:
$fh = fopen($newfile, 'w') or die("Can't create file");
for testing if you can create a file there or not.
用于测试您是否可以在那里创建文件。
If you can't create the file, that's probably because the directory is not writeable by the web server user (usually "www" or similar).
如果您无法创建该文件,那可能是因为该目录不可被 Web 服务器用户写入(通常是“www”或类似名称)。
Do a chmod 777 folderto the folder you want to create the file and try again.
做一个chmod 777 folder你要创建的文件,然后重试该文件夹。
Does it work?
它有效吗?
回答by Cyborg
Use the function is_fileto check if the file exists or not.
使用该函数is_file检查文件是否存在。
If the file doesn't exist, this sample will create a new file and add some contents:
如果文件不存在,此示例将创建一个新文件并添加一些内容:
<?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.
}
?>

