Tag Archives: fopen

PHP Basics Series – File Manipulation

PHP file manipulation functions are one of the most raw functions that we have. The functions use the same names (and formating) as the C++ functions.

There a great amount of Filesystem Functions that can be used to manipulate a file, but, in order to direct to daily uses, the focus will be set over:

  • Manipulating a common text file.
  • Manipulating a csv file.
  • Deleting a file.

Manipulating a common text file

Consider the scenario: Create a text file with the Loren Ipsum passage as content.

It’s not a hard task, but some steps are needed to do that.

  1. Create the file
  2. Open the file for writing
  3. Place contents on file
  4. Close file

Good thing is that steps 1 and 2 are set in one action (even knowing that is possible to create the file outside of the script and then open it to write) making the course of action a bit smaller.

[Note]: If you open a file, you are required to close it.

Writing

<?php

$pathToFile = ‘/tmp/newTextFile.txt’;
// if on windows adapt to c:\\tmp\\newTextFile.txt – Remember to always escape the backslash otherwise the path will be wrong.

$handler = fopen($pathToFile, ‘w+’); // check the lists of available flags on the fopen function. the w+ will create and open a file to write

$contents = ‘Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.’;

fwrite($handler, $contents); // putting the contents on the file

fclose($handler);
?>

With this small script the application will easily create a file (or clean the file and start over with this flag) and write the contents on it. There is another way to the same with one single line:

<?php
file_put_contents($pathToFile, $contents);
?>

This function works just like the fopen, fwrite and fclose all together, but it will create and override new contents over the existing ones (if file exists) unless a flag to append is specified.

Is a great function to place all lines at once, but is memory expensive if you are placing line by line (since it will opening, writing and closing for each line, instead of open, write each line and then close).

Consider now that is necessary to append another text into that file that have just been created. To do that is necessary to append new content, so the flag on the fopen will change.

Updating

<?php
$handler = fopen($pathToFile, ‘a+’); // this will open the file to write and place the pointer at the end of the file

// just a twist to place line by line
$lines = array(‘line 1’, ‘line 2’, ‘line 3’, ‘line 4’, ‘line 5’, ‘line 6’, ‘line 7’);

foreach ($lines as $index => $content)
{
fwrite($handler, $content);
}

fclose($handler);
?>

The same can be done by placing the file_put_contents inside the foreach and removing the fopen and fclose, but instead of having 1 fopen and 1 fclose you would have 7 of them altogether with the fwrite.

With both scripts above we have covered the writing and updating the file, now all is left is to read the file.

Reading

Reading the file is simple and it’s almost the same concept as the writing a file, but instead of using fwrite it will be using fread.

<?php
$handler = fopen($pathToFile, ‘r+’); // open the file and place the pointer at the beginning of the file.

$lines = array();
while (!feof($handle)) // while the file ain’t over
{
$lines[]= fread($handle, 8192); // trying to read 8192 chars until next – used to create lines, but also can be used filesize($handle) that will read all – with no need of while loop
}
fclose($handler);

// or reading all at once

$handler = fopen($pathToFile, ‘r+’);
$contents = fread($handler, filesize($pathToFile));
fclose($handler);
?>

As we have a sister function for writing all content at once, we also have a function to read all content at once with one single line.

<?php
$contents = file_get_contents($handler);
?>

The file_get_contents works fine, but will return all content into a string which can make the work very hard if the file is too big.

Manipulating CSV files

We have gone through the whole process of writing, reading and updating a file, but why should we take a look on CSV files directly? The answer is simple: Nowadays CSV files are one of the easier way to communicate data between systems and to safely transport data to the user that need it exported.

PHP carries a series of functions that easily handle CSV files making the scripting and processing of files simpler and faster.

Writing and Updating

Using the same concept as the file_put_contents above the fputcsv works in a similar way, but you can easily place all columns values using an array, which makes the design process a bit easier when retrieving data from a database.

<?php
$handle = fopen($pathToFile, ‘w+’);

$line1 = array(‘column1′,’column2’);
$line2 = array(‘column1′,’column2’);
$lines = array($line1,$line2);

foreach ($lines as $index => $line)
{
fputcsv($handle, $line);

// formats a line (passed as a fields array) as CSV and write it (terminated by
// a newline) to the specified file handle . By default all columns are separated
// by a comma ‘,’
}

flcose($handle);
?>

Since fputcsv uses the fopen to handle the file, to update a file would be similar as above, just the write function that would stay as the fputcsv.

Reading

Reading contents from a CSV file is a simple as writing and appending and it will return line by line of the file into an array where each delimiter will be split into a entry on the array.

<?php
$handler = fopen($pathToFile, ‘r+’);

$lines = array();
while(($data = fgetcsv($handle)) !== false)
{
$lines[] = $data;
}

fclose($handler);
?>

Delete files

To end it up let’s learn how to delete files, but as a huge note, I must say, once is deleted, is truly gone, there is no way to recover it.

To delete a file with PHP all you need is a path, correct permissions and a single line of script.

<?php unlink($pathToFile); ?>

PHP unlink works similar to Unix C unlink() function and it will look for the file (or folder) in the specified path and completely remove it from there.

Play a bit with the file manipulation and learn fully how it works. Most likely you will be using it to gather db info into a report, creating new stream files (videos, music), etc.

Have fun.