PHP 8.5.0 Beta 1 available for testing

Voting

: min(seven, seven)?
(Example: nine)

The Note You're Voting On

Anonymous
7 years ago
Note that is_resource() is unreliable. It considers closed resources as false:

<?php

$a
= fopen('http://www.google.com', 'r');
var_dump(is_resource($a)); var_dump(is_scalar($a));
//bool(true)
//bool(false)

fclose($a);
var_dump(is_resource($a)); var_dump(is_scalar($a));
//bool(false)
//bool(false)

?>

That's the reason why some other people here have been confused and devised some complex (bad) "solutions" to detect resources...

There's a much better solution... In fact, I just showed it above, but here it is again with a more complete example:

<?php

$a
= fopen('http://www.google.com', 'r');
var_dump(is_resource($a)); var_dump(is_scalar($a)); var_dump(is_object($a)); var_dump(is_array($a)); var_dump(is_null($a));
//bool(true)
//bool(false)
//bool(false)
//bool(false)
//bool(false)

?>

So how do you check if something is a resource?

Like this!

<?php

$a
= fopen('http://www.google.com', 'r');
$isResource = is_resource($a) || ($a !== null && !is_scalar($a) && !is_array($a) && !is_object($a));
var_dump($isResource);
//bool(true)

fclose($a);

var_dump(is_resource($a));
//bool(false)

$isResource = is_resource($a) || ($a !== null && !is_scalar($a) && !is_array($a) && !is_object($a));
var_dump($isResource);
//bool(true)

?>

How it works:

- An active resource is a resource, so check that first for efficiency.
- Then branch to check what the variable is NOT:
- A resource is never NULL. (We do that check via `!== null` for efficiency).
- A resource is never Scalar (int, float, string, bool).
- A resource is never an array.
- A resource is never an object.
- Only one variable type remains if all of the above checks succeeded: IF it's NOT any of the above, then it's a closed resource!

Just surfed by and saw the bad and hacky methods other people had left, and wanted to help out with this proper technique. Good luck, everyone!

PS: The core problem is that is_resource() does a "loose" check for "living resource". I wish that it had a $strict parameter for "any resource" instead of these user-workarounds being necessary.

<< Back to user notes page

To Top