HTML Goodies - PHP Tutorial
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
Now that you know how to create files and read and write records in those files, It would be useful to know how to manipulate entire files within the files system. This includes copying and deleting them, checking their status and the manipulation of the directories containing them. That's what we'll take a look at here.
Checking File Status
The usability of any computer program, whether it's related to the web or not, is greatly enhanced when the programmer writing it takes the time to look for obvious error conditions before plunging into some operation. This hold completely true for our PHP programs. For example, it is simply good practice to check, before opening a file to write to it, that the file exists and that it is writable. Using your own code to check these things allows you to write your own routine to handle error conditions and thereby inform the user in a nice friendly way of the error condition. The user will appreciate your gently message a lot more than if your code simply crashes and returns a system error code to them!
There are three functions you can use to check a file's status. They are: file_exists, is_readable and is_writable. These functions each take one argument, which tells the function the name of the file it is to test. They each return a true/false (boolean) result. Here's an example that looks to see if a file called myfile.txt exists, and if so, checks if it is readable:
$fileName = "myfile.txt";
print "The file $fileName exists,";
print " and is readable.";
print " but is not readable.";
print "The file $fileName does not exist.";
(By the way, you'll notice that I have "nested" one "if" statement inside another one. This is quite a common thing to do -- note, however, how I use indents to make it easily human-readable. The computer doesn't care about the layout of the code, only the sequence of characters and white space. For human eyes, though, the layout makes a big difference -- it all goes towards being your own best friend!)