Creating a Function That Performs Multiple File Tests

Listing 13.7 creates a function that brings together the file-related functions we've just looked at into one script.

Listing 13.7. A Function to Output the Results of Multiple File Tests

 1: <?php 2: function outputFileTestInfo($f) { 3:     if (!file_exists($f)) { 4:         echo "<p>$f does not exist</p>"; 5:         return; 6:     } 7:     echo "<p>$f is ".(is_file($f) ? "" : "not ")."a file</p>"; 8:     echo "<p>$f is ".(is_dir($f) ? "" : "not ")."a directory</p>"; 9:     echo "<p>$f is ".(is_readable($f) ? "": "not ")."readable</p>"; 10:    echo "<p>$f is ".(is_writable($f) ? "": "not ")."writable</p>"; 11:    echo "<p>$f is ".(is_executable($f) ? "": "not ")."executable</p>"; 12:    echo "<p>$f is ".(filesize($f))." bytes</p>"; 13:    echo "<p>$f was accessed on ".date( "D d M Y g:i A",fileatime($f))        ."</p>"; 14:    echo "<p>$f was modified on ".date( "D d M Y g:i A",filemtime($f))        ."</p>"; 15:    echo "<p>$f was changed on ".date( "D d M Y g:i A",filectime($f) )        ."</p>"; 16: } 17: $file = "test.txt"; 18: outputFileTestInfo($file); 19: ?>

If this code were saved to the document root of your web server as filetests.php and run through your web browser, the output would look something like Figure 13.2 (provided you had a file called test.txt also in the document root).

Figure 13.2. Output of filetests.php.

Notice that we used the ternary operator as a compact way of working with some of these tests. Let's look at one such test, found in line 7, in more detail:

echo "<p>$f is ".(is_file($f) ? "" : "not ")."a file</p>";

We use the is_file() function as the left-side expression of the ternary operator. If it returns true, an empty string is returned. Otherwise, the string "not " is returned. The return value of the ternary expression is added to the string to be printed with concatenation operators. This statement could be made clearer but less compact, as follows:

$is_it = is_file($f) ? "" : "not "; echo "<p>".$f." is ".$is_it." a file</p>";

We could, of course, be even clearer with an if statement, but imagine how large the function would become if we used the following:

if (is_file($f)) {         echo "<p>$f is a file</p>"; } else {         echo "<p>$f is not a file</p>"; }

Because the result of these three approaches is the same, the approach you take becomes a matter of preference.

Sams Teach Yourself PHP, MySQL And Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: