File Handling in PHP

By: Andi, Stig and Derick Emailed: 1730 times Printed: 2344 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Let’s begin with the basic file-accessing functions. Originally, those functions only worked on normal files, so their names begin with “f,” but PHP extends this to almost everything. The most used functions for file access afopen() Opens a handle to a local file, or a file from an URL

  • fread() Reads a block of data from a file

  • fgets() Reads one single line from a file

  • fwrite() / fputs() Writes a block of data to a file

  • fclose() Closes the opened file handle

  • feof() Returns true when the end of the file has been reached

Working with files is easy, as the following example shows:

<?php

/* Open a file */

$fp = fopen ('data.dat', 'r');

if (!$fp) {

die ("The file could not be opened.");

}

/* Read a line from the file */

$line = fgets($fp);

/* Close the file handle */

fclose($fp);

?>

In line 3, a file handle ($fp) is associated with the stream and the stream is associated with the counter.dat file that is on disk. The first parameter is the path to the file. The second parameter passed to fopen() is the mode. The mode specifies whether a stream is opened for reading, writing, both reading and writing, or appending. The following modes exist:

  • r Opens the stream in read-only mode. The file pointer is placed at the beginning of the stream.

  • r+ Opens the stream for reading and writing. The file pointer is placed at the beginning of the stream.

  • w Opens the stream in write-only mode. The file is cleared and the file pointer is placed at the beginning of the stream. If the file does not exist, an attempt is made to create the file.

  • w+ Opens the stream for reading and writing. The file is cleared and the file pointer is placed at the beginning of the stream. If the file does not exist, an attempt is made to create the file.

  • a Opens in write-only mode. The file pointer is placed at the end of the stream. If the file does not exist, an attempt is made to create the file.

  • a+ Opens for reading and writing. The file pointer is placed at the end of stream. If the file does not exist, an attempt is made to create it.

 

The b modifier can be used with the mode to specify that the file is binary. Windows systems differentiate between text and binary files; if you don’t use the b modifier for binary files in Windows, your file may become corrupted. Consequently, to make your scripts portable to Windows, it’s wise to always use the b modifier when you work on a binary file, even when you are developing code on an operating system that doesn’t require it. On UNIX OSs (Linux, FreeBSD, MacOSX, and so on), the b modifier has no effect whatsoever.

Here’s another small example:

<?php

/* Open a file in read/write mode and binary mode, and place

* the stream pointer at the beginning of the stream. */

$fp = fopen("/tmp/tempfile", "rb+");

/* Try to read a block of 4096 bytes from the file */

$block = fread($fp, 4096);

/* Write that same block of data to the stream again

* just after the first one */

fwrite($fp, $block);

/* Close the stream */

fclose($fp);

?>

A third optional parameter, true, is available for fopen() that tells PHP to look in your include path for the file. The following script first tries to open php.ini (in read-only mode) from /etc , then from /usr/local/etc , and finally from the current directory (the dot in the path specifies the current directory). Because php.ini is not a binary file, we do not use the b modifier for the mode:

<?php

/* Set the include path */

ini_set('include_path', '/etc:/usr/local/etc:.');

/* Open handle to file */

$fp = fopen('php.ini', 'r', TRUE);

/* Read all lines and print them */

while (!feof($fp)) {

$line = trim(fgets($fp, 256));

echo ">$line<\n";

}

/* Close the stream handle */

fclose($fp);

?>

This script uses feof() , which is a function we haven’t seen before. feof() tests whether the end of a file has been reached during the last fread() or fgets() call. We use fgets() here, with 256 as  the second parameter. This number specifies the maximum length if the line that fgets() reads. It is important to choose this size carefully. PHP allocates this memory before reading, so if you use a value of 1,000,000, PHP allocates 1MB of memory, even if your line is only 12 characters long. The default is 1,024 bytes, which should be enough for almost all appliances.

Try to decide whether you really need to load the entire file into memory when processing a file. Suppose you need to scan a text file for occurrences of a defined phrase with a regular expression. If you load the file into memory with the file_get_contents() function and then run the preg_match_all() function, you actively waste many resources. It would be more efficient to use a while

(!feof($fp)) { $line = fgets($fp); }

loop, which doesn’t waste memory by loading the entire file into memory. It would speed up the regular expression matching as well.


PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Andi, Stig and Derick
Execution Lifetime of a PHP script
preg_split() and explode() in PHP
preg_replace() and preg_replace_callback() in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
tmpfile() in PHP
Renaming and Removing Files in PHP
Locking files in PHP
File Handling in PHP
Handling BLOB in PHP and MySQL
Using Sessions in PHP
Using Cookies in PHP
Using PEAR::Crypt_HMAC in PHP
Using HMAC Verification in PHP
Input Validation in PHP
__autoload() METHOD in PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
Different versions of PHP - History and evolution of PHP
Parent: child process exited with status 3221225477 -- Restarting
preg_split() and explode() in PHP
Convert XML to CSV in PHP
History and origin of PHP
public, protected, and private Properties in PHP
PHP file upload (Large Files)
isset() function in PHP
Assignment operators in PHP
Static Methods in PHP
Execution Lifetime of a PHP script
Encrypting and decrypting in PHP
A Basic Example using PHP in AWS (Amazon Web Services)
Function to return number of digits of an integer in PHP
Get the first and last day of the month in PHP
Most Emailed Articles (in PHP)
Reading and Writing .gz files in PHP
History and origin of PHP
Getting Started with PHP
Traversing Arrays Using foreach in PHP
Traversing Arrays Using list() and each() in PHP
Assignment operators in PHP
if Statements in PHP
public, protected, and private Methods in PHP
Static Methods in PHP
Locking files in PHP
Renaming and Removing Files in PHP
Creating or Opening a File in PHP
Opening a Remote File in PHP
Extract files from a .zip file using PHP
Reading .CSV file in PHP