Once you master the art of working with files, a wider world of PHP web development opens up to you. Files aren't as flexible as databases by any means, but they do offer the chance to easily and permanently store information across scripts, which makes them popular amongst programmers.
Files, as you can imagine, can store all sorts of information. However, most file formats (e.g. picture formats such as PNG and JPEG) are binary, and very difficult and/or impossible to write using normal text techniques - in these situations you should use the library designed to cope with each format.
One reminder: if you are using an operating system that uses backslash \ as the path separator (e.g. Windows), you need to escape the backslash with another backslash, making \\. Alternatively, just use /, because Windows understands that just fine too.
Topics covered in this chapter are:
Reading and writing files
Temporary files
How to make a counter
Handling file uploads
File permissions
Author's Note: CPUs work in billions of operations per second - a 3GHz CPU is capable of performing three billion operations every second. RAM access time is measured in nanoseconds (billionths of a second) - you can usually access some data in RAM in about 40 nanoseconds. Hard drive access time, however, is measured in milliseconds (thousandths of a second) - most hard drive have about a 7ms access time.
What this means is that hard drives are much, much slower than RAM, so working with files from your hard drive is the slowest part of your computer, excluding your CD ROM. Databases are able to store their data in RAM for much faster access time, whereas storing hard drive data in RAM is tricky.
Files are good for storing small bits of information, but it is not recommended that you use them too much for anything other than your PHP scripts themselves - counters are fine in files, as are other little things, but anything larger would almost certainly benefit from using a database. Having said that, please try to avoid the newbie mistake of putting everything into your database - if you find yourself trying to figure out what field type is right to store picture data, please have a rethink!
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Reading files >>
Previous chapter: Next chapter
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.