0

使用此代码时,我不断收到 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);
?>
4

3 回答 3

1

根据您在编辑之前的原始问题:

由于该文件尚不存在,因此您的while条件将不起作用,这就是您收到这些错误消息的原因。

而且由于您对文件使用随机数,因此您永远不会知道首先要打开哪个文件。只需删除while循环。

尝试这个:

<?php
$random = rand(1, 999999999999);
$location = "saves/".$random;

$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
于 2013-12-29T03:08:22.303 回答
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);
?>
于 2013-12-29T03:10:23.433 回答
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);
于 2013-12-29T03:21:27.757 回答