PHP and MySQL (56 Blogs) Become a Certified Professional

All you Need to Know about File Handling in PHP

Last updated on Oct 08,2020 3.8K Views


In reality, PHP scripts need to work with data retrieved from disk files, SQL result sets, XML documents, and many other types of data. PHP has numerous built-in functions to access these data sources. Let’ understand File Handling in PHP in the following order:

 

File Handling in PHP: Opening Files

php logo-EdurekaThe fopen() function is used to open a file. The first parameter contains the name of the file to be opened and the second parameter tells in which mode the file should be opened. fopen() function creates a pointer which points to the file mentioned.

Example:

<?php
// a file is opened using fopen() function
$file = fopen(“demo.txt”,'w');
?>

The modes in which a file can be opened in PHP are:

ModesDescription
rRead-only. The file pointer starts at the beginning of the file
r+Read/Write. The file pointer starts at the beginning of the file
wWrite only. It opens and clears the contents of the file; or creates a new file if it doesn’t exist
w+Read/Write. It opens and clears the contents of the file; or creates a new file if it doesn’t exist
aAppend. It opens and writes to the end of the file or creates a new file if it doesn’t exist
a+Read/Append. It preserves file content by writing to the end of the file
xWrite only. Creates a new file. Returns FALSE and an error if file already exists
x+Read/Write. Creates a new file. Returns FALSE and an error if file already exist

 

File Handling in PHP: Closing Files

The fclose() function is used to close a file which is pointed by an open file pointer. It takes the file as an argument which has to be closed and closes that file.

NOTE: 

  • A file has to be closed first using the fclose() function if it has been written via fwrite() function and you have to read the contents of the file.

  • fclose() doesn’t work for remote files. It only works on files which are accessible by the server’s file system.

Example:

<?php
$file= fopen("demo.txt", "r");
// the file is closed using fclose() function
fclose($file);
?>

Moving on with File Handling in PHP, the next part is Reading Files.

 

Reading Files

PHP’s file manipulation API is extremely flexible: it lets you read files into a string or into an array, from the local file system or a remote URL, by lines, bytes, or characters.

  • fread(): The fread() function is used to read the contents of the data. The first parameter is the file pointer and the other is the file size in bytes.

<?php
$file= "demo.txt";
$file = fopen( $file, 'r' );
$filedata = fread( $file, 300 );
// reads the first 300 bytes of the file
?>

  • feof() function can be used to check if the “End-Of-File” (EOF) has been reached. This is very useful as we can loop through a file of unknown length. We can do this on every file in any mode.

<?php
$file = fopen(“demo.txt”,”r”) or exit (“ERROR: cannot open file”);
while(!feof($file))
{
echo fgets($file)
}
fclose($file);
?>

  • fgetc(): The fgetc() function is used to read a character from a file.

<? php
$file = fopen("demo.txt", "r") or exit("ERROR: cannot open file");
while(!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

  • file_get_contents(): To read the local disk files in PHP, file_get_contents() function is used. This function accepts the name and path of a disk file, and reads the entire file into a string variable at once.

<?php
//read file into string
$str = file_get_contents(‘demo.txt’) or die(‘ERROR: cannot find file’);
echo $str;
?>

  • file(): An alternative method of reading data from a file is PHP’s file() function. It accepts the name and path of the file and reads the entire file into an array, which has each element of the array representing one line of the file. We iterate through the array using foreach loop to access the elements of the array.

<?php
//read file into an array
$arr=file(“demo.txt”) or die(“ERROR: cannot find file”);
foreach($arr as $line)
{
echo $line;
}
?>

  • Reading Remote Files: Both file_get_contents() and file() support reading data from URLs, using either the HTTP or FTP protocol. It reads an HTML file of the Web into an array.

<?php
//read file into array
$arr= file (“https://www.google.com”) or die (“ERROR: cannot find file”);
foreach($arr as $line)
{
echo $line;
}
?>

NOTE: In case of slow network links, it is more efficient to read a remote file in “chunks,” to maximize the efficiency of available network bandwidth. fgets() function can read a specific number of bytes from a file.

<?php
//read file into array (chunks)
$str=””;
$file=fopen(“http://www.google.com”) or die(“ERROR: cannot open file”);
while(!feof($file))
{
$str=fgets($fgets($file,512);
//it opens only 512 bytes of data
}
fclose($file);
echo $str;
?>

 

 

Writing Files

  • fwrite(): The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

<?php
$file = fopen("demo.txt", "w") or die("ERROR: cannot open file");
$text = "this is the first linen";
fwrite($file, $text);
fclose($file);
?>

  • PHP Overwriting: “demo.txt” contains some data. All the existing data will be ERASED and we start with an empty file.

<?php
$file = fopen("demo.txt", "w") or die("ERROR: cannot open file");
$text = "this is the first linen";
fwrite($file, $text);
fclose($file);
?>

  • file_put_contents(): The file_put_contents() function accepts a filename and the data to be written to the file.

<?php
//write string to file
$data=”this is n the n first line n”;
file_put_contents(“output.txt”,$data) or die(“ERROR: cannot write file”);
echo “data written to file”;
?>

 

Other File Handling and Directory Operations

  • Calculating File Size: The filesize() function calculates the size of a file in bytes. It takes file name as an argument.

<?php
// get file size
if (file_exists(“demo.txt”)) {
echo “File is “ . filesize(“demo.txt”) . “bytes.”;
} else {
echo “Named file does not exist. “;
}
?>

  • Finding the Absolute File Path: The realpath() function is used to retrieve the absolute file path to a file.

<?php
// get file path
if (file_exists(“demo.txt”)) {
echo “File path: “ . realpath(“demo.txt”);
} else {
echo “Named file does not exist. “;
}
?>

NOTE: We can also use the pathinfo() function. It returns an array containing the file’s path, name, and extension.

<?php
// get file path info as array
if (file_exists(“demo.txt”)) {
print_r(pathinfo(“demo.txt”));
} else {
echo “Named file does not exist. “;
}
?>

  • Retrieving File Attributes: We can get detailed information about a particular file, including its ownership, permissions, and modification and access times, using stat() function. It returns this information as an associative array.

<?php
// get file information
if (file_exists(“demo.txt”)) {
print_r(stat(“example.txt”));
} else {
echo “Named file does not exist. “;
}
?>

  • Checking modes: We can check if a file is readable, writable or executable with the help of is_readable(), is_writable(), and is_executable() functions.

<?php
// get file information
// output: 'File is: readable writable'
if (file_exists(“demo.txt”)) {
echo “File is: “;
// check for readable bit
if (is_readable(“example.txt”)) {
echo “ readable “;
}
// check for writable bit
if (is_writable(“demo.txt”)) {
echo “ writable “;
}
// check for executable bit
if (is_executable(“demo.txt”)) {
echo “ executable “;
}
} else {
echo “Named file does not exist. “;
}
?>

  • Checking if it is file or not: The is_dir() function returns true if the argument passed to it is a directory. The is_file() function returns true if the argument passed to it is a file.

<?php
// test if file or directory
if (file_exists(“demo.txt”)) {
if (is_file(“demo.txt”)) {
echo “It's a file.”;
}
else {
echo “ERROR: File does not exist.”;
}
?>

  • Copying Files: The copy() function copies a file from one location to another location. It has the file source and destination path as two arguments

<?php
// copy file
if (file_exists(“demo.txt”)) {
if (copy(“demo.txt”, “new_demo.txt”)) {
echo “File successfully copied.”;
} else {
echo “ERROR: File could not be copied.”;
}
} else {
echo “ERROR: File does not exist.”;
}
?>

  • Renaming Files or Directories: The rename() function is used to rename or movee a file (or directory). I takes the old and new path names as arguments.

<?php
// rename/move file
if (file_exists(“demo.txt”)) {
if (rename(“demo.txt”, “../new_demo.txt”)) {
echo “File successfully renamed.”;
} else {
echo “ERROR: File could not be renamed.”;
}
} else {
echo “ERROR: File does not exist.”;
}
// rename directory
if (file_exists('mydir')) {
if (rename('mydir', 'myotherdir')) {
echo 'Directory successfully renamed.';
} else {
echo 'ERROR: Directory could not be renamed.';
}
} else {
echo 'ERROR: Directory does not exist.';
}
?>

  • Removing Files or Directories: The unlink() function is used to remove a file. It takes the filename name as an argument.

<?php
// delete file
if (file_exists(“demo.txt”)) {
if (unlink(“demo.txt”)) {
echo “File successfully removed.”;
} else {
echo “ERROR: File could not be removed.”;
}
} else {
echo “ERROR: File does not exist.”;
}
?>

  • Locking and unlocking files: The flock() function locks a file before reading or writing it so that it cannot be accessed by another process. Doing this reduces the possibility of data corruption that might occur if two processes attempt to write different data to the same file at the same instant. The first parameter takes the file name. The second parameter to flock() specifies the type of lock: LOCK_EX creates an exclusive lock for writing, LOCK_SH creates a non-exclusive lock for reading, and LOCK_UN destroys the lock.

<?php
//open and lock file
//write string to file
//unlock and close file
$data=”This is n the n first line”;
$file=fopen(“demo.txt”,”w”) or die(“ERROR: cannot open file”);
flock($file,LOCK_EX) or die(“ERROR: cannot lock file”);
fwrite($file,$data) or die(“ERROR: cannot write file”);
flock($file,LOCK_UN) or die(“ERROR: cannot unlock file”);
fclose($file);
echo “data written to file”;
?>

 

Reading and writing files are basic tasks that any PHP developer should know how to accomplish; this article covered both these tasks, and many more. It began with a demonstration of how to read local and remote files, as well as how to create new files or append data to existing ones. It then moved on to directory manipulation under PHP and explained many of PHP’s file and directory functions.

With this, we come to an end of this File Handling in PHP article. I hope file handling shouldn’t be an issue. Check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”File Handling in PHP” and I will get back to you.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

All you Need to Know about File Handling in PHP

edureka.co