In PHP, get_resource_id() returns the unique integer ID of a resource, such as an open file handle. Each resource PHP creates receives its own number.
Available since PHP 8.0. Before PHP 8.0, people wrote (int) $resource to get the same number. get_resource_id() makes that intent clear and is type safe. IDs are handy for logging and debugging, but the exact numbers depend on what your script has already opened.
Syntax
Call get_resource_id() with the values you need. Start with this line.
PHP
$id = get_resource_id($resource);
Call
What it does
get_resource_id($handle)
Returns the integer ID of the open file handle.
get_resource_id($a) === get_resource_id($b)
Checks whether two variables point at the same resource.
get_resource_id("text")
Throws a TypeError, because a string is not a resource.
A resource is a special PHP value that points to something outside PHP, such as a file or a stream. The ID is a positive integer. Do not hard-code its value, because it depends on what else your script has opened.
Library declarations
PHP
get_resource_id(resource $resource): int
Parameters
Parameter
Description
resource
Required. The resource to read the ID from, for example the handle returned by fopen(). A closed resource still has an ID.
Return Value
Return Value
Description
int
The unique integer ID of the resource.
PHP Examples
Example 1 — Reading a Resource ID
Open a small in-memory stream and ask for its ID. The checks print the same output on every machine.
The handle is closed with fclose(). The variable still exists, but PHP now reports it as a closed resource.
gettype() prints resource (closed) to describe that state.
The ID did not change when the resource was closed, so the comparison is true.
A string is not a resource, so get_resource_id("abc") throws a TypeError, which the catch block handles.
Frequently Asked Questions
It returns the unique integer ID that PHP gave to a resource, such as a file handle returned by fopen().
PHP 8.0. In older versions you could write (int) $resource to get the same number.
No. The ID depends on how many resources the script has already created, including streams PHP opens for itself. Use the ID for debugging only and never hard-code its value.
PHP 8 throws a TypeError, because the argument must be of type resource. Check with is_resource() first if you are not sure what you have.
Yes. A closed resource is still a resource value, so it keeps its ID. Use get_resource_type() or gettype() to learn that it is closed.