PHP Learn It! PHP File Write
Google

Writing to Files in PHP

In this lessons we will learn how to write content to files.

The fwrite() function

Learn PHP and MySQL fast!

Learn how you can start building rich interactive database driven sites like a professional developer easily and quickly...

>> Order your copy now for just $39.95 <<

Writing text to files is fairly easy in PHP. We can easily write text to files using the fwrite() function. However, you must make sure to open file in writable mode before writing. You will see which modes to use when writing to files and how to write to files in examples below.

But first, let's examine the fwrite() the function closely.

fwrite($handle, $string, $length);

The fwrite() function takes three arguments, the file handle, the string to be written and the number of bytes to be written, which is optional.

Now, let's work with some examples below on how to write text to files.

Writing text to a file

The first example demonstrates how to write a single line of text to a file.

<?php
$handle = fopen("myfile.txt", 'w+');

if($handle)
{

	if(!fwrite($handle, "Student Name: Mark Fendisen"))
		die("couldn't write to file.");

	echo "success writing to file";
}

?>
<pre>

The above code creates a new file myfile.txt in writable mode using "w+" and writes "Student Name: Mark Fendisen" into the file.

That was fairly easy I would say. Wasn't it?

Note: "w+" truncates the file to zero, that is, deletes everything in the file before writing. If the file doesn't exists, it create a new file.

Writing at the beginning of a file

Using file open mode "a+", you can append text to either beginning or end of a file. We will see how we can do in the examples below

The first example we tackle is, how to write text at the beginning of a file.

The first thing we need to do is open the file in append mode using 'a+'. In other words, open an existing file so that we can add more stuff to it.

The code below writes the string "Student ID: 12345" in the beginning without truncating the file, which means that anything already in the file is left alone, and the new string in written in the beginning of the file.

When you open a file with mode 'a+', the file pointer is placed at the end of the file but remember we want to write at the beginning of the file. To move the file pointer back to the beginning for writing, we can use the function rewind() as seen below.

<?php
$file_name= "myfile.txt";
if(file_exists($file_name))
{
	//open file for writng and place pointer at the end
	$handle = fopen($file_name, 'a+');

	if(!$handle)
	{
		die("couldn't open file <i>$file_name</i>");
	}
	
	//place pointer at the beginning of the file.
	rewind($handle);

	//write to file
	fwrite($handle, "Student ID: 12345");
	echo "success writing to file";
}
else
{
	echo "file <i>$file_name</i> doesn't exists";
}
fclose($handle);
?>

Writing at the end of a file

As seen in the above example, the mode "a+" automatically places the file pointer at the end of the file so we don't have to do anything extra in this case.

The code below writes "Student GPA: 2.9" at the end of the file.

<?php
$file_name= "myfile.txt";
if(file_exists($file_name))
{
	//open file for writng and place pointer at the end
	$handle = fopen($file_name, 'a+');

	if(!$handle)
	{
		die("couldn't open file <i>$file_name</i>");
	}
	
	fwrite($handle, "Student GPA: 2.9");
	echo "success writing to file";
}
else
{
	echo "file <i>$file_name</i> doesn't exists";
}
fclose($handle);
?>

Write string with line breaks

The examples you saw so far write text in one straight line. What if we want line breaks?

Well, we can write text one per line in a file by using carriage return, '\n' or '\r'.

If you are using PC, use "\n". For Macintosh, use "\r". But just to be on the safe side, you can use both together like this "\r\n" regardless of what system you're running your code on. This will guarantee it works under both PCs and Macintosh.

<?php

$file_name = "myfile.txt";
if(file_exists($file_name))
{
	//open file for writng and place pointer at the end
	$handle = fopen($file_name, 'w');

	if(!$handle)
	{
		die("couldn't open file <i>$file_name</i>");
	}
	$str.= "Student Name: Mark Fendisen\r\n";
	$str.= "Student ID: 12345\r\n";
	$str.= "Student GPA: 2.9\r\n";

	fwrite($handle, $str);
	echo "success writing to file";
}
else
{
	echo "file <i>$file_name</i> doesn't exists";
}
fclose($handle);
?>

Reading and writing to a file at the same time

Most often you will find yourself reading and writing to a file at the same time. The example below shows you how to parse data in a file, i.e. read file line by line and overwrite small part of text in a file with new string.

For our example below we will assume we have file which contains the following information about a student.

Student Name: Mark Fendisen
Student ID: 12345
Student GPA: 2.9

What we want to do is update his GPA from 2.9 from 3.1. How would we do it?

First we need to open the file in both read and write mode using "r+". Next, we read the file line by line using fgets function until we reach the student gpa line. We then use string replace function to replace 2.9 with 3.1 and write the new string back to the file.

With me? That's okay if you're not :) Let's examine the code below and you will understand what we have done.

<?php
$file_name= "myfile.txt";
if(file_exists($file_name))
{
	/* Open file for both reading and writng. 
	 * Place pointer at the beginning of the file.
	 */
	$handle = fopen($file_name, 'r+');

	if(!$handle)
	{
		die("couldn't open file <i>$file_name</i>");
	}
	
	while(1)
	{
		//read line
		$line = fgets($handle);
		//if end of file reached then stop reading anymore
		if($line == null)break;
		
		//replace student gpa with new updated gpa
		if(preg_match("/Student GPA:/", $line))
		{
			$new_line = str_replace("Student GPA: 2.9", "Student GPA: 3.1", $line);
		}
		else
		{
			//set file content to a string
			$str.= $line;
		}
	}
	
	//append new updated gpa to file content
	$str.= $new_line;
	
	//set pointer back to beginning
	rewind($handle);

	//delete everything in the file.
	ftruncate($handle, filesize($file_name));

	//write everything back to file with the updated gpa line
	fwrite($handle, $str);
	echo "success writing to file";
}
else
{
	echo "file <i>$file_name</i> doesn't exists";
}
fclose($handle);
?>

output

Student Name: Mark Fendisen
Student ID: 12345
Student GPA: 3.1

The above code is fairly large. I would recommend to go over it slowly and read the internal comments in the code to understand how it is done.

In summary, in this lesson we covered, how to write text to files in different scenarios. Knowing how to work with files can be very useful when developing. I would advise to do some practice examples to get a hang of things before moving on.

From HTML to PHP programming...
Learn how to build websites in PHP

<< PHP File Open Top