Reading and Writing Entire Files in PHP

This section shows you how to work with an entire file at once, as opposed to manip­ulating just a few lines of a file. PHP provides special functions for reading or writing a whole file in a single step.

Reading a File

To read the contents of a file into a string, use file_get_contents(). Pass it a file­name, and it returns a string containing everything in the file. Example 9-2 reads the file in Example 9-1 with file_get_contents(), modifies it with str_replace(), and then prints the result.

Example 9-1. page-template.html for Example 9-2

<html>

<head><title>{page_title}</title></head>

<body bgcolor=”{color}”>

<h1>Hello, {name}</h1>

</body>

</html>

Example 9-2. Using file_get_contents() with a page template

// Load the template file from the previous example

$page = file_get_contentsCpage-template.html’);

// Insert the title of the page

$page = str_replace(‘{page_title}’, ‘Welcome’, $page);

// Make the page blue in the afternoon and

// green in the morning

if (date(‘H’ >= 12)) {

$page = str_replace(‘{color}’, ‘blue’, $page);

} else {

$page = str_replace(‘{color}’, ‘green’, $page);

}

// Take the username from a previously saved session

// variable

$page = str_replace(‘{name}’, $_SESSION[‘username’], $page);

// Print the results

print $page;

With $_SESSION[‘username’] set to Jacob, Example 9-2 prints:

<html>

<head><title>Welcome</title></head>

<body bgcolor=”green”>

<h1>Hello, Jacob</h1>

</body>

</html>

1. Writing a File

The counterpart to reading the contents of a file into a string is writing a string to a file. And the counterpart to file_get_contents() is file_put_contents(). Example 9-3 extends Example 9-2 by saving the HTML to a file instead of printing it.

Example 9-3. Saving a file with file_put_contents()

// Load the template file we used earlier

$page = file_get_contentsCpage-template.html’);

// Insert the title of the page

$page = str_replace(‘{page_title}’, ‘Welcome’, $page);

// Make the page blue in the afternoon and

// green in the morning

if (date(‘H’ >= 12)) {

$page = str_replace(‘{color}’, ‘blue’, $page);

} else {

$page = str_replace(‘{color}’, ‘green’, $page);

}

// Take the username from a previously saved session

// variable

$page = str_replace(‘{name}’, $_SESSION[‘username’], $page);

// Write the results to page.html

file_put_contents(‘page.html’, $page);

Example 9-3 writes the value of $page (the HTML) to the file page.html. The first argument to file_put_contents() is the filename to write to, and the second argu­ment is what to write to the file.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *