spraff spraff - 1 year ago 91
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);

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)

The trace in
tells us


I guess I can use
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 Source

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:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download