PHP Resources

In PHP, Resource is a special data type that refers to any external resource. A resource variable acts as a reference to external source of data such as stream, file, database etc. PHP uses relevant functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable.

PHP's Zend engine uses reference counting system. As a result, a resource with zero reference count is destroyed automatically by garbage collector. Hence, memory used by resource data type need not be freed manually.

Common Resource Types

Various types of resources can be handled in a PHP script, with the help of corresponding functions. Following table shows a select list −

Resource Type Name Created By Destroyed By Definition
stream fopen(), tmpfile() fclose() File handle
stream opendir() closedir() Directory handle
curl curl_init() curl_close() Curl session
mysql link mysql_connect() mysql_close() Link to MySQL database
mysql result mysql_db_query() mysql_free_result() MySQL result
xml xml_parser_create() xml_parser_free() XML parser
zlib gzopen() gzclose() gz-compressed file

Getting Resource Type

PHP provides get_resource_type() function that returns resource type of a variable.

Syntax

get_resource_type(resource $handle): string

where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type.

Example

Following example shows how to identify resource type of a file handle −

<?php
$fp = fopen("test.txt", "w");
var_dump($fp);
echo "Resource type: " . get_resource_type($fp) . "<br>";
fclose($fp);
?>
resource(5) of type (stream)
Resource type: stream

Practical Example

Here's how you can check different resource types in your code −

<?php
// Create a temporary file resource
$tempFile = tmpfile();
echo "Temp file type: " . get_resource_type($tempFile) . "<br>";

// Create a string stream resource
$stringStream = fopen('php://memory', 'r+');
echo "String stream type: " . get_resource_type($stringStream) . "<br>";

// Clean up
fclose($tempFile);
fclose($stringStream);
?>
Temp file type: stream
String stream type: stream

Conclusion

Resources in PHP provide a way to work with external data sources efficiently. They are automatically managed by PHP's garbage collector and can be identified using get_resource_type() function for debugging purposes.

Updated on: 2026-03-15T09:19:47+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements