使用此代码时,我一直遇到3个错误:
Warning: fopen() [function.fopen]: Filename cannot be empty
Warning: fwrite(): supplied argument is not a valid stream resource
Warning: fclose(): supplied argument is not a valid stream resource
我不知道该怎么办。我是一个PHP菜鸟。
<?php
$random = rand(1, 9999999999);
$location = "saves/".$random;
while (file_exists($location)) {
$random = rand(1, 999999999999);
$location = "saves/".$random;
}
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
答案 0 :(得分:1)
根据编辑前的original question:
由于该文件尚不存在,您的while
条件将无效,这就是您收到这些错误消息的原因。
由于您使用的是文件的随机数,因此您永远不会知道要打开哪个文件。只需删除while
循环。
试试这个:
<?php
$random = rand(1, 999999999999);
$location = "saves/".$random;
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
答案 1 :(得分:0)
从您拥有的代码看,$ location只存在于while循环的范围内。尝试
<?php
$location = "";
while (file_exists($location)) {
$random = rand(1, 999999999999);
$location = "saves/".$random;
}
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
答案 2 :(得分:0)
首先,您必须为$location
变量设置值,或者由于尚未创建文件,请尝试以下操作:
$random = rand(1, 999999999999);
$location = "saves/".$random;
$content = "some text here";
//if(file_exists($location)) $fp = fopen($location,"wb");
$fp = fopen($location, 'wb') or die('Cannot open file: '.$location); //implicitly creates file
fwrite($fp,$content);
fclose($fp);