fwrite error when trying to create a file – PHP

  php

Q(Question):

I’m getting this error:
Warning: fwrite(): supplied argument is not a valid stream resource in /mypath on line 1222

My code is this:

$File = "custom.css";
$Handle = fopen($File, 'w') or die("can't open file");
if (fwrite($Handle, $css_file) === FALSE)
{
echo "Cannot write to file ($File)";
exit;
}

The error text also appears below the error. The CHMOD on the directory is 777.

Am I overlooking somethng?

A(Answer):

Hey.

Are you sure those are the correct lines from the code?

I ask because the fopen function either returns a stream resource, which would not cause this error, or it returns FALSE, which in your code would trigger the or die command.
This error shouldn’t be possible using that code.

To be sure, thought, try printing the contents of the $Handle before the fwrite just to see exactly what it is:

<?php
$File = "custom.css";
$Handle = fopen($File, 'w') or die("can't open file");
var_dump($Handle); exit;
if (fwrite($Handle, $css_file) === FALSE)
{
echo "Cannot write to file ($File)";
exit;
}
?>

A(Answer):

I will try that out. Line 1222 is:
if (fwrite($Handle, $css_file) === FALSE)
I’ll find out what’s in the Handle.

A(Answer):

When using the var dump it gives me:
resource(53) of type (stream)
I’m afraid I don’t understand what this means. It it supposed to show something else?

A(Answer):

It’s working now. All I did was add the code you suggested, looked at the error message and took the code out and tired it again and it’s working.
I’m glad it’s working but I’d like to know why.

Thanks for your help.

A(Answer):

Hmm… odd.

Did you copy the original code from somewhere? Like a web-page?
It is possible that there was a "special" character in there, invisible, which PHP took as a part of the variable name… Or just some odd charset mismatch.

A(Answer):

I can’t remember. I think I copied the code from php.net. I would have thought there wouldn’t be any invisible characters there.
The only think that worries me is that if it didn’t work and them for seemingly no reason starts to work, I hope it doens’t later on stop with no warning.

Thanks for all youe help.

LEAVE A COMMENT