Recent Posts

Showing posts with label boolean given. Show all posts
Showing posts with label boolean given. Show all posts

How to solve: Warning: [function] expects parameter 1 to be resource, boolean given

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

... a cURL handle and a cURL multi handle.

When var_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)
That's all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.

The "... expects parameter 1 to be resource, boolean given" error is typically the result of an unchecked operation that was supposed to create a resource, but returned false instead. For instance, the fopen function has this description:

Return Values
Returns a file pointer resource on success, or FALSE on error.
So in this code, $fp will either be a resource(x) of type (stream) or false:

$fp = fopen(...);
If you do not check whether the fopen operation succeed or failed and hence whether $fp is a valid resource or false and pass $fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

Warning: fread() expects parameter 1 to be resource, boolean given
You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);