fwrite() expects parameter 1 to be resource, string given in c://

Phoenix picture Phoenix · Dec 9, 2015 · Viewed 17.5k times · Source

I am using latest version of php.. and i stuck on this error

Warning: fwrite() expects parameter 1 to be resource, string given in c:\ this error shows me 6 times

Warning: fclose() expects parameter 1 to be resource, string given in // this error reapeat only one time.

I am trying to get last id of last line but i am facing that error.. here is my php code :

<?php
include_once('../../fucrenzione.php');
/*
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";*/
$filename ="data.txt" or die("Unable to open file!");
$line="";
fopen($filename, 'a+');
    for($i=0;$i<=5;$i++ ){

        $va=rand(1,20);
        $re= rand(2,50);
        $data = [
                'val1' => $va,
                'val2' => $re, 
                'body' => getToken(10),
                'Id'=> $i,
                'timestamp' => time()
                ];

     /* echo   "<pre>".*/$line = serialize($data);
     $line .= "\n";
    fwrite($filename, $line);

    }
fclose($filename);
?>

I tried to use also fputs() but i still get that error.

Answer

AbraCadaver picture AbraCadaver · Dec 9, 2015

The error tells you the issue. fopen() returns a resource:

$handle = fopen($filename, 'a+');

Then fwrite() expects the first argument to be that resource:

fwrite($handle, $line);

Also, I think the or die("Unable to open file!"); would be better on the fopen() line rather than the assignment line.