All you Need to Know about File Handling in PHP

Last updated on Oct 08,2020 3.7K Views

All you Need to Know about File Handling in PHP

edureka.co

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

The 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: 

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.

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

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

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

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

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

<?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

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

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

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

<?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. “;
}
?>

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

<?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. “;
}
?>

<?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.”;
}
?>

<?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.”;
}
?>

<?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.';
}
?>

<?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.”;
}
?>

<?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.

BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial