Using PHP: Part 2: File Input and Output

Learning PHP

Using PHP

PHP: Hypertext Preprocessor (PHP) is a server-side scripting language frequently used as part of web development and as a command-line tool for common tasks.

PHP has many different functions and ways of doing things. Consulting the documentation is always the most recommended way of learning about new functions. In nearly all cases, though, functions that start with “f” are those that can be used with files in some way or another.

File Input

Depending on the context, there are many different ways to read files in PHP. To get the entire file as a string, a function like file_get_contents() may be preferred. To read the file as an array, the function file() might be better. Many of the fget* style of functions like fgets() or fgetc() can also be used depending on the task and purpose.

URLs are considered file-paths in PHP. This means that they can be used to retrieve data from an external source using its URL instead of a local file and PHP will treat it as such. Nearly all of the functions that work on file input also work on URLs as well.

File Output

To write a smaller string into a file, fwrite() is usually a good choice. To write a larger string, file_put_contents() might be a better choice.

Opening and Closing Files

When working with local files, they need to be opened and closed. In most cases fopen() and fclose() are used for this. The exceptions are when using file_get_contents() or file_put_contents() that internally invoke these functions.

Play with the example on!