Using PHP is_resource() to Check Resource Types
This article explains the PHP is_resource() function, its syntax, return values, and demonstrates its usage through practical examples for checking file handles, database connections, and image resources, helping developers correctly identify resource types and avoid errors.
In PHP, is_resource() is a very useful function for determining whether a variable is of the resource type, which represents external resources such as database connections, file handles, image resources, and more.
The syntax of the function is:
<code>bool is_resource ( mixed $var )</code>The $var parameter is the variable to be examined. The function returns a boolean value: true if the variable is a resource, false otherwise.
Example 1: Checking a file handle variable
<code>$file = fopen("data.txt", "r");
if (is_resource($file)) {
echo "文件句柄为资源类型";
} else {
echo "文件句柄不是资源类型";
}
fclose($file);
</code>This code opens a file with fopen() , assigns the file handle to $file , and then uses is_resource() to verify that $file is a resource. It outputs a message accordingly and finally closes the handle with fclose() .
Example 2: Checking a database connection variable
<code>$host = "localhost";
$user = "root";
$pass = "password";
$dbname = "test";
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (is_resource($conn)) {
echo "数据库连接为资源类型";
} else {
echo "数据库连接不是资源类型";
}
mysqli_close($conn);
</code>The script connects to a MySQL database using mysqli_connect() , stores the connection in $conn , and then checks with is_resource() whether the connection is a resource, printing the appropriate message before closing it with mysqli_close() .
Example 3: Checking an image resource variable
<code>$width = 500;
$height = 300;
$image = imagecreatetruecolor($width, $height);
if (is_resource($image)) {
echo "图像资源为资源类型";
} else {
echo "图像资源不是资源类型";
}
imagedestroy($image);
</code>This example creates a true‑color image with imagecreatetruecolor() , assigns it to $image , and uses is_resource() to confirm that $image is a resource. It then destroys the image with imagedestroy() .
Through these examples, the article demonstrates how is_resource() can be applied in real‑world scenarios to safely verify that variables representing external resources are indeed valid resources, helping developers avoid errors when handling files, database connections, or images.
Summary
The article provides a detailed introduction to the PHP is_resource() function, its syntax, return values, and three practical code examples covering file handles, database connections, and image resources, illustrating how to reliably determine resource types in backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.