File Handling in PHP
By: Andi, Stig and Derick in PHP Tutorials on 2008-11-23
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.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Send push notifications using Expo tokens in PHP
PHP convert string to lower case
A Basic Example using PHP in AWS (Amazon Web Services)
Different versions of PHP - History and evolution of PHP
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Resume or Pause File Uploads in PHP
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Comments