user1561466
user1561466

Reputation: 81

fclose Warning: fclose(): supplied argument is not a valid stream resource

I am getting the warning on my pages

Warning: fclose(): supplied argument is not a valid stream resource

Using the following code

$fp = fopen('data.txt', 'w');
$write = '2';
fwrite($fp, $write);
fclose($fp);  

Update code

if(isset($_REQUEST['go1']))
{
    $fp = fopen('data.txt', 'w');
    $write = '1';
    $fp1 = fopen('file.php', 'w');
    $write1 = '<br><img src="/1/online.png" style="position:absolute; z-index:-2;" />';
}
if(isset($_REQUEST['go2']))
{

    $fp = fopen('data.txt', 'w');
    $write = '2';
    $fp1 = fopen('file.php', 'w');
    $write1 = '<br><img src="/1/offline.png" style="position:absolute; z-index:-2;" />';
}

fwrite($fp, $write);
fclose($fp);
fwrite($fp1, $write1);
fclose($fp1);

$fp = fopen('data.txt', 'r');
$contents = fread($fp, filesize('data.txt'));
fclose($fp);
if($contents == '1')
    include('file.php');
else if($contents == '2')
    include('file.php');
else
    echo 'Something else...';

getting the error on line 27 and line 29 line 27

fclose($fp);    

line29

fclose($fp1);

Upvotes: 3

Views: 22214

Answers (3)

When your if() condition returnes false, there's no $fp file opened so there's nothing to close. PHP does not understand what file you wanted to close cuz there's nothing opened.

Upvotes: 2

voodoo417
voodoo417

Reputation: 12101

Your problem is in the "if-else" statement (file not opened)... check your code

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881313

The only possibility that springs immediately to mind is that the fopen failed for some reason, leaving $fp set to FALSE.

This could occur, for example, if you weren't allowed to create or overwrite the data.txt file (permissions and so forth).

From the fopen and fclose documentation for PHP (slightly paraphrased):

The fopen() call returns a file pointer resource on success, or FALSE on error.

The file pointer for fclose() must be valid, and must point to a file successfully opened by fopen() or fsockopen().

(my italics). You really should check the return value from fopen to make sure it worked before trying to use the file handle.


Based on your updated code, you should check that one of those request variables (go1 or go2) is actually set. If neither is, then you will not open the file, but you'll still try to close it.

And, though you said it wrote to the file, you might want to confirm that by deleting it before you start a run. You may just be seeing the previous file.

Upvotes: 0

Related Questions