In PHP programming, resource types are special data types that represent references to external resources, such as files, network connections, or database connections. These resources are typically created and managed by PHP built-in functions.
The following PHP functions return a type of resource handle for subsequent use:
The following example demonstrates how to use the fopen() function to open a text file and read its contents:
<?php // Open the file and get the file handle $fileHandle = fopen("test.txt", "r"); // Check if the file opened successfully if ($fileHandle) { // Read the file contents using the file handle $fileContents = fread($fileHandle, filesize("test.txt")); // Close the file fclose($fileHandle); } else { // Failed to open the file echo "Unable to open file!"; } ?>
Resource types are an efficient way in PHP to interact with external systems. Functions like fopen, fsockopen, mysqli_connect, and curl_init enable flexible interaction with the file system, network services, and databases. Mastering resource usage and proper release helps build more stable and high-performance PHP applications.