Exactly as the question states: How can you check if a variable in PHP contains a file pointer? Some like is_string()
or is_object()
.
views:
310answers:
3You can use stream_get_meta_data()
for this.
<?php
$f = fopen('index.php', 'r');
var_dump(stream_get_meta_data($f));
?>
array
'wrapper_type' => string 'plainfile' (length=9)
'stream_type' => string 'STDIO' (length=5)
'mode' => string 'r' (length=1)
'unread_bytes' => int 0
'seekable' => boolean true
'uri' => string 'index.php' (length=9)
'timed_out' => boolean false
'blocked' => boolean true
'eof' => boolean false
You can prefix it with @ to supress warnings if the variable is not a resource - then just check if it returned false.
You can use get_resource_type()
- http://us3.php.net/manual/en/function.get-resource-type.php. The function will return FALSE if its not a resource at all.
$fp = fopen("foo", "w");
...
if(get_resource_type($fp) == 'file' || get_resource_type($fp) == 'stream') {
//do what you want here
}
The PHP documentation says that the above function calls should return 'file', but on my setup it returns 'stream'. This is why I check for either result above.
As already said, you can use stream_get_meta_data, or get_resource_type to check the type of resource you are dealing with.
A better and more reliable way is to use SPL to work with files, it can save some headache and make your life more pleasant. This possibility is not very well documented yet, so many developers create their own wrappers for the file objects, but you may find all you need here:
http://www.php.net/~helly/php/ext/spl/classSplFileObject.html
http://www.php.net/~helly/php/ext/spl/classSplFileInfo.html
The first one has provides the methods for reading, writing, seeking the file, and so on...
The second one provide meta-information about the object you are working with, among the others there is a method:
$object->isFile();