What is the is_resource method in PHP?
The is_resource method can be used to check if a variable is a resource or not.
Syntax
is_resource(mixed $value): bool
This method returns true if the passed value is a resource. Otherwise, it returns false.
Refer here for the list of resources available in PHP.
For closed resources, the is_resource method returns false.
Code
<?php$test = fopen("foo", "w");printIsResource($test);$test = tmpfile();printIsResource($test);fclose($test);printIsResource($test);$test = false;printIsResource($test);function printIsResource($test){echo "The Value is: ";var_dump($test);echo "Is Resource: ";var_dump(is_resource($test));echo "---------\n\n";}?>
Explanation
In the code above:
-
We open a file,
foo, and call theis_resourcemethod. For this case, we will gettrueas the result. -
We use the
tmpfilemethod to create a temporary file and call theis_resourcemethod. For this case, we will gettrueas the result. -
Then, we use
fcloseto close the created temporary file and call theis_resourcemethod again. Now, we will getfalseas the result because theis_resourcemethod returnsfalsefor closed resources.