1

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?

1
  • 1
    or FALSE on error. . so type will be Boolean always. Php returns are Boolean values when the context is function Commented Nov 25, 2016 at 18:10

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.