Jump to content

[SOLVED] fwrite - am I going crazy?


CowbellMaster

Recommended Posts

Here's the php file:

 

<?php
$LogFile = fopen("blah.log","a");
someFunction("testing error text");
fclose($LogFile);

function someFunction($blah)
{ fwrite($LogFile, $blah); }

?>

 

Here's my error:

 

Warning: fwrite(): supplied argument is not a valid stream resource in /home/Cowbell/public_html/phpTest/f.php on line 7

 

I don't understand why I'm getting an error.

 

I've tried

chmod 777 *

and

chmod 777 .

and I'm getting the same result.

 

Please help.  Thanks.

Link to comment
https://forums.phpfreaks.com/topic/121638-solved-fwrite-am-i-going-crazy/
Share on other sites

The handle $LogFile is unknown in the function unless you declare it global or pass it in. I would pass it:

<?php
$LogFile = fopen("blah.log","a");
someFunction($LogFile,"testing error text");
fclose($LogFile);

function someFunction($fp,$blah)
{ fwrite($fp, $blah); }

?>

 

Ken

$LogFile is not available inside of the function because its' scope is the main program.

 

The point of functions are to encapsulate code and data that accomplish some distinct function (which is why they are called functions.) By opening the file in the main code but putting the fwrite into a function, you are splitting code and data that accomplish one task into two different scopes.

 

There are three ways to fix this -

 

1) Don't use a function at all. Writing a user function that just contains one line that calls another function is pointless.

 

2) Pass the file handle to the function as a parameter.

 

3) Use a class to encapsulate the code and related data into a single object.

If you need to run this function numerous times, a class is very helpful, consider this basic example for creating a function that will open the file, write data, and close it:

 

<?php
someFunction("blah.log","a","testing error text");

someFunction("blahher.log","a","testing nothing here error");

function someFunction($file,$mode,$blah)
{
$fp = fopen($file,$mode);
//perhaps filter out $blah in some way
//$blah = escape($blah);
fwrite($fp,$blah);
fclose($fp);
return true;
}
?>

 

As an example, I don't really expect it to be used in place of your code, but you should see how it helps to use a class for generalizing a function.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.