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操作,然后重试.
它有用吗?
小智 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,您应该关心文件的修改时间将被更改的事实。
使用该功能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)
| 归档时间: |
|
| 查看次数: |
66089 次 |
| 最近记录: |