O'Reilly logo

Wicked Cool PHP by Brian Ward, William Steinmetz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required