Retrieving File Information

$filename = __FILE__;

It is rather unusual to use PHP for accessing directory and file informationat least as long as the vast majority of PHP scripts run via HTTP in a web server and not using the command line interface (CLI) or PHP.

However, PHP offers a variety of helper functions that provide information about a file. Most of them are just calling the relevant operating system functions.

Reading Information About Files
  $filename = __FILE__;
  $data = array(
    'fileatime' => fileatime($filename),
    'filegroup' => filegroup($filename),
    'filemtime' => filemtime($filename),
    'fileowner' => fileowner($filename),
    'filesize' => filesize($filename),
    'is_dir' => var_export(is_dir($filename), true),
    'is_executable' =>
var_export(is_executable($filename), true),
    'is_file' => var_export(is_file($filename),
    'is_link' => var_export(is_link($filename),
    'is_readable' => var_export(is_readable
       ($filename), true),
    'is_uploaded_file' => var_export
       (is_uploaded_file($filename), true),
    'is_writable' => var_export
       (is_writable($filename), true)
  echo '<table>';
  foreach ($data as $function => $result) {
  echo '</table>';

The following list shows the most relevant helper functions in this regard:

  • fileatime($filename) Last access to the file

  • filegroup($filename) Group that owns the file

  • filemtime($filename) Last change to the file

  • fileowner($filename) File owner

  • filesize($filename) Size of the file

Another set of helper functions also takes a filename, so the files do not have to be opened before you use these functions:

  • is_dir($path) Whether the path is a directory

  • is_executable($filename) Whether the filename is an executable

  • is_file($path) Whether the path is a (regular) file

  • is_link($filename) Whether the filename is a symbolic link

  • is_readable($filename) Whether the file is readable

  • is_uploaded_file($path) Whether the path is a file uploaded via HTTP (see Remembering Users (Cookies and Sessions))

  • is_writable($filename) Whether the file is writable

Figure 6.5 contains the result of the code at the beginning of This.

Information about the current script (fileinfos.php).