Opening and Closing Files

Opening Files

Before you can use PHP to read a file, you must first open it. To open a file, you use the fopen() function.

$file_handler = fopen($file, $mode) 

You must assign the function to a variable, as above. This is referred to as a file pointer. You use the file pointer to reference the open file throughout your script.

The fopen() function takes two arguments:

  • $file is the name (and path, if required) of the file.

  • $mode is one of a list of available modes:

    • r— Open the file as read-only. You cannot write anything to the file. Reading begins at the beginning of the file.

    • r+ — Open the file for reading and writing. Reading and writing begin at the beginning of the file. You will delete existing contents if you write ...

Get Advanced PHP for Web Professionals now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.