PHP is_resource() Function

PHP

PHP is_resource() - Check Resource

The is_resource() function in PHP is a built-in utility used to determine if a variable is a resource. Resources are special variables in PHP that hold references to external files, database connections, image canvases, and other system-level entities. Using is_resource() correctly ensures your code safely handles these resource variables without unexpected errors.

Prerequisites

  • Basic knowledge of PHP syntax and variables
  • Familiarity with PHP data types, especially resources
  • PHP environment set up locally or on a server (PHP 7.x or PHP 8.x recommended)

Setup Steps

  1. Ensure PHP is installed on your system. You can verify by running php -v in the terminal.
  2. Create a PHP file, e.g., resource_test.php, in your project folder.
  3. Open the file in your preferred code editor.
  4. Use the following examples to start testing the is_resource() function.

What is the is_resource() Function?

is_resource() is a PHP function that checks whether a variable is a resource type. It returns true if the variable is a resource, and false otherwise.

Function Syntax

bool is_resource ( mixed $var )

Parameter:

  • $var: The variable to be checked.

Return Value: Returns true if $var is a resource, false otherwise.

Explained Examples

Example 1: Checking a File Handle

<?php
$file = fopen("example.txt", "w"); // Open a file resource
if (is_resource($file)) {
    echo "The variable is a resource.\n";
} else {
    echo "The variable is NOT a resource.\n";
}
fclose($file); // Always close resource when done
?>

Explanation: fopen() returns a file pointer resource. is_resource() confirms this, returning true.

Example 2: Checking a Database Connection Resource

<?php
$conn = pg_connect("host=localhost dbname=testdb user=postgres password=secret");
if (is_resource($conn)) {
    echo "Database connection is a resource.\n";
} else {
    echo "Not a resource.\n";
}
?>

Note: For PostgreSQL or other database extensions that use resources, is_resource() helps validate connection handles before usage.

Example 3: Variable Not a Resource

<?php
$var = 12345;
if (is_resource($var)) {
    echo "It's a resource.\n";
} else {
    echo "Not a resource.\n"; // This will be printed
}
?>

Example 4: Using is_resource() with Image Resources

<?php
$image = imagecreate(100, 100);
if (is_resource($image)) {
    echo "This is an image resource.\n";
} else {
    echo "Not a resource.\n";
}
imagedestroy($image);
?>

Best Practices

  • Always use is_resource() to verify resource variables before accessing or manipulating them to avoid runtime errors.
  • Close or free resources explicitly when done (e.g., fclose(), imagedestroy()) to prevent resource leaks.
  • Be aware that PHP 8.0 introduced some changes in internal resource handling; always test your code when migrating PHP versions.
  • Do not confuse resource types with objects or other variable types; is_resource() returns false for objects.

Common Mistakes

  • Checking variables that are not likely to be resources, resulting in unnecessary conditionals.
  • Failing to close resources after usage, causing performance issues.
  • Assuming a resource is always valid without checking with is_resource(), which may lead to warnings or errors if resource was closed or no longer valid.
  • Using is_resource() to check objects, which will always return false since resource and object are different types.
  • Not testing for resource validity when working with database connections or file handlers.

Interview Questions

Junior Level Questions

  • Q: What does is_resource() do in PHP?
    A: It checks whether a variable is a resource type and returns true or false.
  • Q: Name a common example of a resource in PHP.
    A: A file handle returned by fopen().
  • Q: Can is_resource() return true for an object?
    A: No, it only returns true for resources, not objects.
  • Q: Why is it important to check a variable with is_resource() before using it?
    A: To avoid errors by confirming it is a valid resource before performing operations.
  • Q: How do you close a file resource in PHP?
    A: Using fclose() function.

Mid Level Questions

  • Q: How does is_resource() behave with closed resources?
    A: It returns false because once a resource is closed, it is no longer a valid resource.
  • Q: Can is_resource() be used to check database connections?
    A: Yes, for database extensions that represent connections as resources, e.g., PostgreSQL.
  • Q: What type of values will is_resource() return false for?
    A: Scalars, arrays, objects, null, or any non-resource variable.
  • Q: How can improper handling of resources affect PHP applications?
    A: It can lead to memory/resource leaks and reduced application performance.
  • Q: What alternatives exist to is_resource() in PHP 8 for some extensions?
    A: Some extensions now use objects instead of resources, so type checking against classes is used instead.

Senior Level Questions

  • Q: Explain how resource handling changed in PHP 8 and its impact on is_resource().
    A: PHP 8 replaced many internal resources with objects (e.g., mysqli, curl), so is_resource() returns false for those, requiring instanceof checks instead.
  • Q: How would you handle resource validation in a legacy PHP 7 codebase versus PHP 8?
    A: In PHP 7, use is_resource(). In PHP 8, check for objects using instanceof or extension-specific functions.
  • Q: What strategies can be implemented to avoid resource leaks in large PHP applications?
    A: Always validate resources before use, close/free them promptly, use try-finally for guaranteed cleanup, and implement centralized resource management.
  • Q: How does is_resource() behave when passed an invalid or corrupted resource handle?
    A: It returns false because the variable is no longer a valid resource.
  • Q: Can you extend the functionality of is_resource() for custom resource-like objects?
    A: Not directly, but you can create custom functions or use interfaces and classes to define resource-like behavior and validate accordingly.

Frequently Asked Questions (FAQ)

Q1: What types of variables does is_resource() recognize?

It recognizes special PHP resource types such as file handles, database connections, image canvases, and other external references.

Q2: Is is_resource() useful in modern PHP versions?

Yes, but less so in PHP 8 and above since many extensions replaced resources with objects. Use it when working with legacy or resource-type extensions.

Q3: How can I create a resource variable?

By calling PHP functions that return resources, such as fopen() for files or pg_connect() for PostgreSQL connections.

Q4: What happens if I pass a closed resource to is_resource()?

The function will return false, because the resource has been freed and is no longer valid.

Q5: Can I rely on is_resource() to determine if a resource is still valid?

Yes, but only to a degree. It tells you whether the variable is a valid resource handle; it does not guarantee that the external entity (e.g., connection) is still active.

Conclusion

The PHP is_resource() function is a critical tool for validating resource variables such as file handles and database connections, which are commonly used in PHP applications. Proper use of is_resource() helps prevent runtime errors and resource leaks by allowing you to verify resource validity before operating on them. While its role has evolved in PHP 8 with shifts toward objects, it remains vital when working with legacy codebases and resource-based extensions.

Always pair is_resource() with proper resource management techniques like closing files and connections to maintain healthy, performant PHP applications.