#50: Placing a File's Contents into a Variable

Let's say that you want to put all of the content of a text file into a variable so that you can access it later. This is a good introduction to file access, because it shows all of the basic steps. Here's how you would place the contents of file.txt into the $file_data variable:

<?php

$file_data = '';

$fd = fopen('file.txt', 'r');
if (!$fd) {
    echo "Error! Couldn't open the file.";
    die;
}

while (! feof($fd)) {
    $file_data .= fgets($fd, 5000);

}

fclose($fd);

?>

The fopen() function is an essential first step in most file access. It acts as a gateway between the system and PHP. When opening a file, you specify how you want to access the file. In this case, we open it for read access. You can also open ...

Get Wicked Cool PHP 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.