PHP is_resource() Function

What is PHP is_resource() Function?

If you want to know whether a variable is a resource or not, use is_resource() function. Resources include file handle, database connection, network socket.

Syntax:

is_resource(variable)

Parameters:

The Function has 1 parameter which is required-

variable (Required): It specifies a variable.

Return Values:

The function returns-

  • TRUE, if the variable is an active resource.
  • FALSE, if the variable is an active resource.

Examples:

Example 1:

<?php
/* Suppose, the file.txt exists in the current directory. */
$handle = fopen("file.txt", "r");
if (is_resource($handle)) {
    echo "The resource is a valid resource.<br />";
}
fclose($handle); // It closes the resource.
if (!is_resource($handle)) {
    echo "The resource is now closed and no longer valid.";
}
?>

Output:

The resource is a valid resource.
The resource is now closed and no longer valid.

Practical usage of PHP is_resource() function:

  • Before operating a file, you can use is_resource() function to make sure that the resource is valid and open.
  • Before working with a database connection or network socket, you can use is_resource() function to make sure that the connection is valid and open.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP is_object() Function

is_resource() is a built-in variable handling function. It is an easy function to determine whether a resource is still open and valid or not.

Reference:

https://www.php.net/manual/en/function.is-resource.php