Reputation: 33395
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?
Upvotes: 1
Views: 1459
Reputation: 6581
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.
Upvotes: 1
Reputation: 14863
What system are you on? It works as expected here:
<?php
$f = fopen('/var/log/mail.err', "a");
var_dump($f);
if ($f === false) {
echo 'Not a valid stream';
}
Outputs:
<br />
<b>Warning</b>: fopen(/var/log/mail.err): failed to open stream: Permission denied in <b>/foobar.php</b> on line <b>2</b><br />
bool(false)
Not a valid stream
Tested on Debian. PHP7.0.
Upvotes: 0