Check Status of File (Readable/Writable) in PHP

Leave a Comment

You can confirm that the entity you are testing is a file, as opposed to a directory, with the is_file() function. is_file() requires the file path and returns a Boolean value:
if ( is_file( "test.txt" ) )
print "test.txt is a file!";

Conversely, you might want to check that the entity you are testing is a directory. You can do this with the is_dir() function. is_dir() requires the path to the directory and returns a Boolean value:
if ( is_dir( "/tmp" ) )
print "/tmp is a directory";
When you know that a file exists, and it is what you expect it to be, you can then find out some things that you can do with it. Typically, you might want to read, write to, or execute a file. PHP can help you with all of these.

is_readable() tells you whether you can read a file. On UNIX systems, you may be able to see a file but still be barred from reading its contents. is_readable() accepts the file path as a string and returns a Boolean value:
if ( is_readable( "test.txt" ) )
print "test.txt is readable";

is_writable() tells you whether you can write to a file. Once again it requires the file path and returns a Boolean value:
if ( is_writable( "test.txt" ) )
print "test.txt is writable";

is_executable() tells you whether you can run a file, relying on either the file's permissions or its extension depending on your platform. It accepts the file path and returns a Boolean value:
if ( is_executable( "test.txt" )
print "test.txt is executable"; 

0 comments:

Post a Comment