Php – fwrite(): supplied argument is not a valid stream resource

fclosefopenfwritePHPwarnings

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

Best Answer

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