我有这样的代码:
$filename = "history-login ".date("d M Y").".txt";
$docroot = "public/file/".$filename;
$txt = "username : ".$admin_session->username."n";
$txt .= "time : ".date("d M Y , h:i:s")."n";
if (file_exists($docroot)){
$myfile = file_put_contents($docroot, $txt.PHP_EOL , FILE_APPEND) or die("Unable to write!");
}else{
$myfile = fopen($docroot, "w") or die("Unable to open file!");
}
fwrite($myfile, $txt);
fclose($myfile);
我收到一条这样的警告信息:
警告:fwrite()要求参数1为资源,给定的整数
警告:fclose()要求参数1为资源,给定的整数
你能帮我想办法解决这个问题吗?
问题是,当文件存在时,$myfile = file_put_contents()
片段正在执行,但正如文档所说-http://php.net/manual/en/function.file-put-contents.php-file_put_contents()
返回int,而不是fwrite()
和fclose()
所期望的资源。因此,只需将这两个函数放入else
分支中,如下所示:
if (file_exists($docroot)){
$myfile = file_put_contents($docroot, $txt.PHP_EOL , FILE_APPEND) or die("Unable to write!");
}else{
$myfile = fopen($docroot, "w") or die("Unable to open file!");
fwrite($myfile, $txt);
fclose($myfile);
}
您的代码跳转到$docroot存在的情况,因此$myfile不是文件资源对象。我认为您只需要在file_put_contents 之后返回
if (file_exists($docroot)){
$myfile = file_put_contents($docroot, $txt.PHP_EOL , FILE_APPEND) or die("Unable to write!");
return;
}else{
$myfile = fopen($docroot, "w") or die("Unable to open file!");
}