Question

I keep getting 3 errors when I use this code:

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

I don't know what to do. I'm a php noob.

<?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);
?>
Was it helpful?

Solution

As per your original question before your edit:

Since the file doesn't exist yet, your while condition won't work and that's why you're getting those error messages.

And since you're using a random number for the file, you will never know which file to open in the first place. Just remove the while loop.

Try this:

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

$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>

OTHER TIPS

From the code you have, it looks like $location only exists inside the scope of the while loop. Try

<?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);
?>

first of all, you must set values to your $location variable or since the file is not yet created try this:

$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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top