创建文件时出错

时间:2015-04-10 14:49:56

标签: php file fatal-error

使用此php代码创建文件时出错:

$userdbfile = file('userfiles/' . $steamprofile['steamid'] . '.txt');
$fhuserdb = fopen($userdbfile, 'a');
fwrite($fhuserdb, $steamprofile['steamid']);
fwrite($fhuserdb, "0");
close($fhuserdb);
header("Location: index.html");
exit;

错误:

  

警告:文件(userfiles / 76561198043436466.txt):无法打开流:第7行/home/u294343259/public_html/admin/lw/login.php中没有此类文件或目录
  警告:fopen():第12行的/home/u294343259/public_html/admin/lw/login.php中的文件名不能为空   警告:fwrite()要求参数1为资源,布线在第13行的/home/u294343259/public_html/admin/lw/login.php中给出   警告:fwrite()期望参数1是资源,布线在第14行的/home/u294343259/public_html/admin/lw/login.php中给出。   致命错误:在第15行的/home/u294343259/public_html/admin/lw/login.php中调用未定义的函数close()

2 个答案:

答案 0 :(得分:2)

file()无法创建新文件!它只读取文件。所以只需删除它并使用fopen(),就像这样

$userdbfile = 'userfiles/' . $steamprofile['steamid'] . '.txt';
$fhuserdb = fopen($userdbfile, 'a');

//checks that the file was successfully opened 
if($fhuserdb) {
    fwrite($fhuserdb, $steamprofile['steamid']);
    fwrite($fhuserdb, "0");
    fclose($fhuserdb);
}
//^ The function is 'fclose()' not 'close()' to close your file
header("Location: index.html");
exit;
  • 还要确保该文件夹具有适当的权限才能写入。

答案 1 :(得分:1)

阅读手册:

  • the file function将整个文件读入数组。第一个警告告诉您所请求的文件不存在
  • the fopen function期望第一个参数为字符串,file返回数组或失败时为falsefopen的第一个参数应该是一个字符串,指定要打开的文件的路径。它会在失败时返回资源(文件句柄)或false
  • fwrite希望您传递有效文件句柄,不要检查fopen的返回值(false case),所以你没有写到实际的文件
  • close不存在,fclose does,再次:这需要在有效文件句柄上调用,这是你不具备的,因此这个线也将失败
  • 只有在没有发送输出的情况下才能调用
  • the header function(仔细阅读 description 下面的位),您的代码会产生警告和错误,从而产生输出。因此,拨打header
  • 已经太晚了

那么现在呢?

将您传递到file的路径转到fopen,检查其返回值并相应地继续:

$userdbfile = 'userfiles/' . $steamprofile['steamid'] . '.txt';
$fh = fopen($userdbfile, 'a');
if (!$fh)
{//file could not be opened/created, handle error here
    exit();
}
fwrite($fh, $steamprofile['steamid']);
fwrite($fh, '0');
fclose($fh);
header('Location: index.html');
exit();