PHP File Handling

PHP File Handling

File handling is an important part of any web application. You often need to open and process a file for different tasks, such as reading configuration data, parsing logs, or importing user lists.

PHP has several powerful functions for creating, reading, uploading, and editing files.


The readfile() Function

The readfile() function reads a file and writes it to the output buffer. This is the simplest way to display the contents of a file on a webpage.

Readfile Example

<?php
echo readfile("dictionary.txt");
?>

The readfile() function is useful if all you want to do is open up a file and read its contents. But for more advanced manipulation, you need the fopen() function.


Opening and Reading Files with fopen()

A better method for opening files is with the fopen() function. This function gives you more options than the readfile() function.

The first parameter of fopen() contains the name of the file to be opened, and the second parameter specifies in which mode the file should be opened.

Common Modes:

Fopen and Fread Example

<?php
$myfile = fopen("webdict.txt", "r") or die("Unable to open file!");

// Read the file entirely echo fread($myfile, filesize("webdict.txt"));

// Always close the file when you're done! fclose($myfile); ?>

Important: The fclose() function is used to close an open file. It is a good programming practice to close all files after you have finished with them to free up server memory.


Exercise

?

Which mode should you use with fopen() if you only want to read the file?