Backend Development 4 min read

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:

<code>bool is_resource ( mixed $var )</code>

It returns true if the variable is a resource, otherwise false .

Example 1: Checking a file handle

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

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

<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 database, checks the connection resource, prints the appropriate message, and finally closes the connection.

Example 3: Checking an image resource

<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, 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.

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

login 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.