spraff spraff - 13 days ago 7
PHP Question

PHP fopen returning TRUE

PHP's fopen is supposed to


Returns a file pointer resource on success, or FALSE on error.


$f = fopen ($logfile, "a");

file_put_contents("/tmp/foo", gettype($f)."--".print_r ($f), TRUE);


The
fopen
is printing
failed to open stream: Permission denied
in the Apache log, which is what I expect in this particular case, however the error-handling logic that comes after isn't working because
if ($f)
succeeds.

The trace in
/tmp/foo
tells us

boolean--1


I guess I can use
is_resource
to make the error handling work, but this looks like a bug in PHP, no? Or is there something else that could bring about this situation?

Answer

I think a minor misuse of print_r is leaving confusion. Note that if you wish to use print_r "inline" then a second parameter is required.

echo print_r($f, 1).' '.TRUE;

That's going to print:

1

The reason it prints a space and then 1 is that $f is FALSE, which in print_r prints nothing. But if you ask a string to print TRUE directly, it converts it to an integer representation, or "1".

Try this:

if ($f) {
  echo 'f!';
} else {
  echo 'no f';
}

You'll find that there is "no f" if fopen fails. Try using this test:

if ($f !== false) {

That way you'll be sure it's a resource.