2
votes

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);
3
Did you check to make sure the file was opened correctly?Burhan Khalid
@Burhan Yes the file is opening and writing the sameuser1561466
Is there anything else in the script? If there is, try to simulate the same thing with only these lines. Also, make sure 'data.txt' is actually written to and not just some old file from previous experiments :)Vatev
@Vatev I have updated the code,Please adviseuser1561466

3 Answers

1
votes

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

1
votes

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.

0
votes

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.