File Manipulation

11.3. File Manipulation

There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't connect to the database. It'd be impossible to keep this information in the database, since it's not available at exactly the time you'd need to write to it. PHP provides functions for file manipulation that can perform the following:
  • Check the existence of a file
  • Create a file
  • Append to a file
  • Rename a file
  • Delete a file

The file_exists.php script checks to see if the file is there
<?php
  $file_name="file_exists.php";

  if(file_exists($file_name)) {
    echo ("$file_name does exist.");
  }
  else {
    echo ("$file_name does not exist.");
  }
?>

As you would expect, the file does exist:
The file exists.php does exist. 
 
PHP provides several functions to tell you about various file attributes. PHP has the ability to read data from, and write data to, files on your system. However, it doesn't just stop there. It comes with a full-featured file-and-directory-manipulation API that allows you to:
  • View and modify file attributes
  • Read and list directory contents
  • Alter file permissions
  • Retrieve file contents into a variety of native data structures
  • Search for files based on specific patterns
All of this file manipulation through the API is robust and flexible. These characteristics are why we're writing this book. PHP has a lot of great commands, including all the file manipulation ones.
11.3.1.1. Permissions
Now that you know a file exists, you may think you're done, but you're not. Just because it's there doesn't mean you can read, write, or execute the file. To check for these attributes, use is_readable to check for read access, is_writable to check for write access, and is_executable to check for the ability to execute the file. Each function takes a filename as its parameter. Unless you know the file is in the same directory as your script, you must specify a full path to the file in the filename. You can use concatenation to put the path and filename together, as in:
$file_name = $path_to_file . $file_name_only;