O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

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 Handling

Powerful as it is, MySQL is not the only (or necessarily the best) way to store all data on a web server. Sometimes it can be quicker and more convenient to directly access files on the hard disk. Cases in which you might need to do this include for modifying images, such as uploaded user avatars, or log files that you wish to process.

First, though, a note about file naming. If you are writing code that may be used on various PHP installations, there is no way of knowing whether these systems are case-sensitive. For example, Windows and Mac OS X filenames are not case-sensitive, but Linux and Unix ones are. Therefore, you should always assume that the system is case-sensitive and stick to a convention such as all-lowercase filenames.

Checking Whether a File Exists

To determine whether a file already exists, you can use the file_exists function, which returns either TRUE or FALSE and is used like this:

if (file_exists("testfile.txt")) echo "File exists";

Creating a File

At this point testfile.txt doesn’t exist, so let’s create it and write a few lines to it. Type in Example 7-4 and save it as testfile.php.

Example 7-4. Creating a simple text file

<?php // testfile.php
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3

_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>

When you run this in a browser, all being well, you will receive the message “File ...

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