Master PHP’s is_resource(): Detect Resource Types with Real Code Examples

This article explains how PHP's is_resource() function checks whether a variable represents an external resource such as a file handle, database connection, or image, and provides clear code samples demonstrating its practical use in each scenario.

php Courses
php Courses
php Courses
Master PHP’s is_resource(): Detect Resource Types with Real Code Examples

Summary

In PHP, is_resource() is a useful function for determining whether a variable is of the resource type, which represents external resources like database connections, file handles, or image resources.

The function signature is: bool is_resource ( mixed $var ) It returns true if the variable is a resource, otherwise false.

Example 1: Checking a file handle

$file = fopen("data.txt", "r");
if (is_resource($file)) {
    echo "文件句柄为资源类型";
} else {
    echo "文件句柄不是资源类型";
}
fclose($file);

This code opens a file, uses is_resource() to verify the handle, outputs the result, and then closes the file.

Example 2: Checking a MySQLi database connection

$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);

The script connects to a database, checks the connection resource, prints the appropriate message, and finally closes the connection.

Example 3: Checking an image resource

$width = 500;
$height = 300;
$image = imagecreatetruecolor($width, $height);

if (is_resource($image)) {
    echo "图像资源为资源类型";
} else {
    echo "图像资源不是资源类型";
}
imagedestroy($image);

This example creates a true‑color image, verifies the image resource, outputs the result, and destroys the image resource.

Through these examples, you can see how is_resource() helps ensure that variables representing external resources are valid before performing operations, preventing errors in PHP applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPCode Examplesis_resourceresource handling
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.