File Handling in PHP
File Handling in PHP
• Opening a file
• Reading a file
• Writing a file
• Closing a file
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the
file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
$filename = "file.txt";
$file = fopen( $filename, "r" );
Mode Purpose
Opens the file for reading only.
r
Places the file pointer at the beginning of the file.
Opens the file for reading and writing.
r+
Places the file pointer at the beginning of the file.
Opens the file for writing only.
Places the file pointer at the beginning of the file.
w
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
Opens the file for reading and writing only.
w+
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attempts to create a file.
Opens the file for writing only.
Places the file pointer at the end of the file.
a
If files does not exist then it attempts to create a file.
Opens the file for reading and writing only.
Places the file pointer at the end of the file.
a+
If files does not exist then it attempts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a
file pointer which is used for further reading or writing to that file.
fclose()
After making a changes to the opened file it is important to close it with the
fclose()function. The fclose() function requires a file pointer as its argument and then
returns truewhen the closure succeeds or false if it fails.
Reading a file
Once a file is opened using fopen() function it can be read with a function called fread().
This function requires two arguments. These must be the file pointer and the length of the
file expressed in bytes.
The files length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
•Open a file using fopen() function.
•Get the file's length using filesize() function.
•Read the file's content using fread() function.
•Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those
contents on the web page.
<?php
$filename = "file.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo "File size : $filesize bytes" ;
echo $filetext;
?>
Output:
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite()
function. This function requires two arguments specifying a file pointer and the string of
data that is to be written. Optionally a third integer argument can be included to specify
the length of the data to write. If the third argument is included, writing would will stop
after the specified length has been reached.
The following example creates a new text file then writes a short text heading inside it.
After closing this file its existence is confirmed using file_exist() function which takes file
name as an argument
Code:
<?php
$filename = "file1.txt";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes<br>" );
echo ( "$filetext<br>" );
echo("file name: $filename");
?>
File Permission: Function chmod()
bool chmod ( string $filename, int $mode );
Definition and Usage
Attempts to change the mode of the specified file to that given in mode.
Parameters
Sr.No Parameter & Description
path
1
A file path.
2 mode
Note that mode is not automatically assumed to be an octal value, so strings
(such as "g+w") will not work properly. To ensure the expected operation,
you need to prefix mode with a zero (0) −
The mode parameter consists of four numbers:
•The first number is always zero
•The second number specifies permissions for the owner
•The third number specifies permissions for the owner's user group
•The fourth number specifies permissions for everybody else
Possible values (to set multiple permissions, add up the following numbers):
•1 = execute permissions
•2 = write permissions
•4 = read permissions
Returns
Returns TRUE on success and FALSE on failure.
Example:
<?PHP
//sets the file to readable, writable, and executable by all users
chmod("file.txt", 0777);
//sets the file to readable, writable, and executable by owner,
//and just readable and writable by everyone else.
chmod("file.txt", 0755);
// Read and write for owner, nothing for everybody else
chmod("file.txt",0600);
// Read and write for owner, read for everybody else
chmod("file.txt ",0644);
// Everything for owner, read for owner's group
chmod("file.txt",0740);
// Everything for owner, read and execute for owner's group
chmod("file.txt", 0750);
?>
Page Visitors Into File
<?php
$filename = "file.txt";
$file = fopen( $filename, "r" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
$filetext++;
echo $filetext;
fclose( $file );
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
fwrite( $file, $filetext);
echo $filetext;
fclose( $file );
?>
PHP Read Single Line – fgets()
PHP fgets() function is used for reading single line from file This function takes two
arguments as described below.
fgets(file, [length])
1. File specifies filename to read content
2. Length Optional parameter, specifies number of bytes to read from file.
//Reads only one line
<?php
$filep = fopen("file1.txt", "r") or die("Unable to open file!");
$t = fgets($filep)
echo $t;
fclose($filep);
?>
//To read all content use while loop
<?php
$filep = fopen("file1.txt", "r") or die("Unable to open file!");
while($t = fgets($filep)){
echo $t;
}
fclose($filep);
?>
PHP Check EndOfFile feof()
The feof() function checks if the "endoffile" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
<?php
$filep = fopen("file1.txt", "r") or die("Unable to open file!");
while(!feof($filep)) {
echo fgets($filep) ;
fclose($filep);
?>
PHP Read Single Character fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the "webdictionary.txt" file character by character, until endof
file is reached:
Example:
<?php
$filep = fopen("file1.txt", "r") or die("Unable to open file!");
while(!feof($filep)) {
echo fgetc($filep);
}
fclose($filep);
?>
Checking Existing Files: file_exists()
Definition and Usage
The file_exists() function checks whether or not a file or directory exists.
This function returns TRUE if the file or directory exists, otherwise it returns FALSE.
Syntax
file_exists(path)
Parameter Description
path Required. Specifies the path to check
<?php
$file = "file.txt";
// Check the existence of file
if(file_exists($file)){
echo “File Exists”;
} else{
echo “File Does not Exists”;
}
?>
Renaming Files with PHP rename()
Function
You can rename a file or directory using the PHP's rename() function, like this:
Syntax:
rename(oldname,newname,context)
Parameter Description
oldname Required. Specifies the file or directory to be renamed
newname Required. Specifies the new name of the file or directory
Optional. Specifies the context of the file handle. Context is a set of options that
context
can modify the behavior of a stream
<?php
$file = "file.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to rename the file
if(rename($file, "newfile.txt")){
echo "File renamed successfully.";
} else{
echo "ERROR: File cannot be renamed.";
}
} else{
echo "ERROR: File does not exist.";
?>
PHP: Delete files with unlink()
The unlink() function deletes a file.
This function returns TRUE on success, or FALSE on failure.
Syntax
unlink(filename,context)
Parameter Description
filename Required. Specifies the file to delete
Optional. Specifies the context of the file handle. Context is a set of options that
context
can modify the behavior of a stream
<?php
$file = "file.txt";
if (!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}
?>