Bookmark and Share

PHP - File Truncate

As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.

Advertise on

PHP - File Open: Truncate

To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

PHP - Truncate: Why Use It?

Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.

For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.

This might not be the most efficient program, but it is a nice usage of truncate.

Bookmark and Share

Download's PHP Book

If you would rather download the PDF of this tutorial, check out our PHP eBook from the store. Print it out, write all over it, post your favorite lessons all over your wall!

Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials