This concluding article in the series illustrates PHP's filefunctions, with examples of how to read and write files on the system. Italso includes an explanation of user-defined functions, return values andfunction arguments, together with some not-so-real-life examples.
In the examples you've just seen, we've made one basic assumption - the file that PHP is trying to read already exists. However, in the big bad world, this assumption can sometimes cost you hours of debug time if the file isn't actually present on the system.
To avoid situations like this, PHP offers the file_exists() function, which can be used to test for the presence of the file and generate an appropriate error message if it isn't found. Let's modify the example above to include this capability:
<?php
// set filename
$filename = "random.txt";
// check for file
if (file_exists($filename))
{
// read file into array
$contents = file($filename);
// get array length
$length = sizeof($contents);
echo "<b>File $filename contains $length line(s)</b><p>";
// display each line with "for" loop
for($counter=0; $counter<$length; $counter++)
{
echo "$contents[$counter]<br>";
}
}
else
{
echo "<b>File not found!</b>";
}
?>
Now try it out - rename or delete your file, and watch as PHP
gracefully exits with your customized error message.
PHP also comes with a bunch of functions that can provide you with detailed information about the type of file - here's a list:
is_dir() - checks whether the specified file is a directory
is_executable() - checks whether the specified file is executable
is_link() - checks whether the specified file is a link
is_readable() - checks whether the specified file is readable
is_writeable() - checks whether the specified file is writable
filegroup() - returns the group
fileowner() - returns the owner of the file
fileperms() - returns the current permissions on the file
filesize() - returns the size of the file
filetype() - returns the type of the file
And here's an example:
<?php
// set filename
$filename = "random.txt";
// check for file
if (file_exists($filename))
{
echo "<b>$filename</b><br>";
// check if it is a directory
if (is_dir($filename))
{
echo "File is a directory ";
}
// check if it is executable
if (is_executable($filename))
{
echo "File is executable ";
}
// check if it is readable
if (is_readable($filename))
{
echo "File is readable ";
}
// check if it is writeable
if (is_writeable($filename))
{
echo "File is writeable ";
}
echo "File size is " . filesize($filename) . " bytes<br>";
echo "File group is " . filegroup($filename) . "<br>";
echo "File owner is " . fileowner($filename) . "<br>";
echo "File permissions are " . fileperms($filename) . "<br>";
echo "File type is " . filetype($filename) . "<br>";
}
else
{
echo "<b>File not found!</br>";
}
?>
Here's the output:
File is readable
File is writeable
File size is 286 bytes
File group is 100
File owner is 538
File permissions are 33188
File type is file