17 File Handling – I
Hiren Joshi
The data which is used by most web sites is stored in a database. Though, in some cases some of the data might be stored in files. Data can be used to read from files and write to files by using various built in function in PHP.
Functions to determine file or directory exists
Function | Description |
is_file($path) | Returns true if $path is a file otherwise returns false. |
is_dir($path) | Returns true if $path is a directory otherwise returns false. |
file_exists($path) | Returns true if $path exists and $path is either file or directory. |
A constant that contains the correct path separator
Constant | Description |
DIRECTORY_SEPARATOR
|
A directory separator irrespective of operating system. Backward slash
for windows OS and forward slash for Linux or MAC OS |
Consider the following code. We have save this file as 1. is_file.php.
<?php
$path = ‘H:\wamp\www\PathshalaWAD\File Handling – I’;
$file = $path.DIRECTORY_SEPARATOR.’1. is_file.php’;
$dir = $path.DIRECTORY_SEPARATOR.’New Folder’;
echo “File is $file”;
$a = is_file($file);
if($a === TRUE)
{
echo “<br> $file exists”;
}
else
{
echo “<br> $file does not exist”;
}
// DIRECTORY $b = is_dir($dir); if($b === TRUE)
{
echo “<br> $dir is directory”;
}
else
{
echo “<br> $dir is not a directory”;
}
// file_exists
$c = file_exists($file);
if($c === true)
{
echo “<br> $file exists”;
}
else
{
echo “<br> $file does not exist”;
}
?>
The output will be:
File is H:\wamp\www\PathshalaWAD\File Handling – I\1. is_file.php
H:\wamp\www\PathshalaWAD\File Handling – I\1. is_file.php exists
H:\wamp\www\PathshalaWAD\File Handling – I\New Folder is directory
H:\wamp\www\PathshalaWAD\File Handling – I\1. is_file.php exists
Function to get a directory listing
Function | Description |
scandir($path) | Returns an array having a list of files and directory in $path, if $path is a valid directory name. Otherwise it return false. |
Following code shows the use of scandir function.
<?php
$cwd = getcwd();
$dir = scandir($cwd);
foreach($dir as $d)
{
echo “<br> $d”;
}
The output will be
1. is_file.php
2. scandir.php
New Folder
New folder (2)
In case, we are interested to display only files within a directory, the code can be used as follow:
<?php
$cwd = getcwd();
$dir = scandir($cwd);
//only file
echo “<br> To display only files”;
$file = array();
foreach($dir as $d)
{
if(is_file($d))
{
$file[] = $d;
}
}
foreach($file as $f)
{
echo “<br> $f”;
}
?>
The output is:
To display only files
1. is_file.php
2. scandir.php
3. scandir shows only file.php
Read and Write an entire file
Functions to read an entire file
Function | Description |
readfile($name) | Reads the file $name and echoed it to the web page |
file_get_contents ($name) | Returns the string having content of a file $name |
file($name) | Returns an array which contains each line as one element of array for file $name |
Consider there is a file ‘city.txt’ having some name of the cities. Following code shows example using file function. In the same manner, you can use file_get_contents and readfile function.
<?php
$cwd = getcwd();
$sep = DIRECTORY_SEPARATOR;
$filename = ‘city.txt’;
$file = $cwd.$sep.$filename;
$f = file($file);
foreach($f as $line)
{
echo “$line <br>”;
}
?>
The output is:
Ahmedabad
Rajkot
Surat
Baroda
Bhuj
Functions to write an entire file
Function | Description |
file_put_contents ($name, $data) | Write the data string $data to the file $name. |
<?php
$cwd = getcwd();
$sep = DIRECTORY_SEPARATOR;
$filename = ‘city.txt’;
$file = $cwd.$sep.$filename;
$newcity = ‘Patan’;
file_put_contents($file,$newcity);
echo “<br> New City added successfully to the file city.txt”; ?>
Then it will overwrite the old content and add $data to the file $file.
Write an array to a file
<?php
$cwd = getcwd();
$sep = DIRECTORY_SEPARATOR;
$filename = ‘names.txt’;
$file = $cwd.$sep.$filename;
$names = array(‘Juhi’,’Neelam’,’Minakshee’);
$names = implode(“\n”,$names);
file_put_contents($file,$names);
?>
The above code will overwrite the file names.txt with $names.
Read a file into an array
<?php
$cwd = getcwd();
$sep = DIRECTORY_SEPARATOR;
$filename = ‘names.txt’;
$file = $cwd.$sep.$filename;
$names = file($file);
foreach($names as $n)
{
echo “$n <br>”;
}
?>
Read and Write part of a file
The functions described earlier is used to read or write an entire file. These functions are helpful when file size is small. When the file size is large, generally it is preferred to read or write a portion of the file. When you use file for read or write, it consumes internal memory. So read and write a portion of a file use less internal memory. To read or write a portion of the file, following functions are used.
Functions to open and close the file
Function | Description |
fopen($path,$mode) | Opens the $path file in $mode and returns a file handle |
feof($file) | Returns true when End Of File for $file is reached. |
fclose($file) | Closes the $file |
To open a file, it is compulsory to specify how you want to open the file. There are various modes to open a file. The below table describes various file open modes.
Mode | Description |
r | Open the file for reading. It starts reading from the beginning of the file. |
r+ | Open the file for reading and writing. It starts reading from the beginning of the file. |
w | Open the file for writing. It starts writing from the beginning of the file. In case the file already exists, this mode delete the existing content. If file does not exist, try to create it. |
w+ | Open the file for writing and reading. It starts writing or reading from the beginning of the file. In case the file already exists, this mode delete the existing content. If file does not exist, try to create it. |
a | Open the file for appending (writing) only. It starts writing from the ending of the existing content, if any. If file does not exist, try to create it. |
a+ | Open the file for appending (writing) and reading. It starts writing or reading from the ending of the existing content, if any. If file does not exist, try to create it. |
x | Open the file for writing. It starts writing from the beginning of the file. In case the file already exists, this mode will not open the file. fopen function will return false and PHP displays warning. |
x+ | Open the file for writing and reading. It starts writing/reading from the beginning of the file. In case the file already exists, this mode will not open the file. fopen function will return false and PHP displays warning. |
b | Used in conjunction with all of the above mode (r,r+,w,w+,a,a+,x,x+). This mode is generally used if file system differentiates between binary and text files. Windows OS differentiate file system while Unix OS does not differentiate. PHP developers recommended to use it to gain maximum portability. This is the default mode. |
t | Used in conjunction with all of the above mode (r,r+,w,w+,a,a+,x,x+). This mode option is used with Windows OS only. |
Functions which read from the file and write to the file
Function | Description |
fread($file , $length) | Reads up to $length bytes from $file |
fgets($file) | Reads a line from $file |
fwrite($file , $data) | Writes the string content $data to the file $file |
The following code shows how to read 10 bytes of file names.txt using fread function.
<?php
$cwd = getcwd();
$sep = DIRECTORY_SEPARATOR;
$name = ‘names.txt’;
$filename = $cwd.$sep.$name;
$file = fopen($filename,’rb’);
$l =fread($file,10);
echo “<br> $l”;
fclose($file);
?>
The output is:
Juhi Neela
Following code shows read line by line of a file using fgets function.
<?php
$cwd = getcwd();
$sep = DIRECTORY_SEPARATOR;
$name = ‘names.txt’;
$filename = $cwd.$sep.$name;
$file = fopen($filename,’rb’);
while(!feof($file))
{
$line = fgets($file);
echo “$line <br>”;
}
fclose($file);
?>
Juhi
Neelam
Minakshee
Following code shows how to write into a file using fwrite
<?php
$cwd = getcwd();
$dir = scandir($cwd);
$file = fopen(‘dir.txt’,’ab’);
foreach($dir as $d)
{
if(is_dir($d))
{
fwrite($file,$d.”\n”);
}
}
fclose($file);
?>
Above code will create a new file dir.txt and add the directory name in the dir.txt file.
Locking Files
When a file is used by more than one user to write simultaneously, it can be corrupted. If one person write into the file and the same time other person open the same file to read it, this situation can get odd result. The reason is that it depends on operating system. To handle simultaneous user, the built-in file locking function flock is used. Flock function make queues of the request to access the file until the lock is released. So, when you code for writing to a file, you should use flock function. Flock can be used for reading a file.
The syntax of flock is:
flock($file, lock_mode)
$file is a file-pointer and lock_mode is operative value of the lock.
flock returns true if lock is acquired successfully otherwise false.
The following table shows flock operation values.
Value of Operation | Meaning |
LOCK_SH | Reading lock. In reading lock mode file can be shared to read file with other users. |
LOCK_EX | Exclusive lock. It is also called writing lock. In this mode, file is not shared with other user. |
LOCK_UN | Unlock. This mode is unlocked the existing lock. |
LOCK_NB | Block lock. This mode prevents blocking while trying to acquire a lock. |
Flock function is called after fopen function and used before writing to a file.
Note that flock is not worked with NFS or other networked file systems. Flock also not worked with older file system such as FAT. In some operating system, flock is implement at process level and it is not worked correctly with multithread server API. Following code segment show how to use flock function.
$cwd = getcwd();
$dir = scandir($cwd);
$file = fopen(‘dir.txt’,’ab’);
flock($file, LOCK_EX);
$new = ‘ABC’;
fwrite($file,$new);
flock($file,LOCK_UN);
fclose($file);
Though, flock is used to solve simultaneous writing into a file, it is not a full-proof solution.
RDBMS is the preferred way to handling simultaneous writing in database.
you can view video on File Handling – I |
References:
1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,
2. W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional, Apress
3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K. Glass:Beginning PHP5, Apache, and MySQL Web Development, Wrox,
4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media
5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove: Professional PHP, Wrox
6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible
7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach
8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications
9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams
10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide, Pearson Education
11. www.php.net
12. http://www.w3schools.com/
13. http://www.tutorialspoint.com/