O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

We've already discussed the include and require functions for pulling information directly into a PHP script. At this junction, we'll focus on working with file content.

Warning

Since working directly with files from your PHP code can create security risks, it's a good idea to find solutions to problems that don't use files directly if possible; for example, storing information in a database instead of file. You must be very careful to not allow misuse of your PHP programs to either read or destroy the contents of important files either accidentally or as part of an attack.

Functions and Precautions

To check for the existence of a file, use the function file_exists, which takes the name of the file to check for its parameter, as shown in Example 11-20. If the file exists, it returns TRUE; otherwise, it returns FALSE.

Example 11-20. 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required