PHP File Handling System


PHP File Handling:– File handling is an important task of any web application. In this tutorial you will learn how to create, access, and manipulate files and directory on your web server using the PHP file system functions.

Firstly open a file using fopen method by passing two parameters(file name,access mode).Based on requirement there are many modes which we can utilise in files.
For example opening a file for reading only, opening a file for reading and writing both etc .These all mode we will discuss later in detail.

  1. fclose()function is used to close a file after performing all operations.
  2. fread()function is used to read a file from first character to entire file .
  3. fread()takes two parameters ; first file name and second is for filesize given for characters length to read from file.

Modes Meaning
r opens the file to read only
r+ Opens the file for reading and writing.
x+ Opens the file for reading and writing. Returns FALSE and an error if file already exists.
x Opens the file for writing only. Returns FALSE and an error if file already exists.
a+ Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If files does not exist then it attempts to create a file.
a Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If files does not exist then it attempts to create a file.
w+ Opens the file for reading and writing and clears the contents of file. If files does not exist then it attempts to create a file.
w Opens the file for writing only and clears the contents of file. If files does not exist then it attempts to create a file.

PHP File Handling | Example

Example of PHP File Handling.

<?php 
if(file_exists("file.txt")){
$handle = fopen("file.txt", "r");//open file in read mode 
echo $handle;
}
else {
	die("Error: The file you are trying to access doesn't exist.");
}
echo "<br>";
echo "<br>";
echo fread($handle,filesize("file.txt"));
?>    

Advertisements

Add Comment

📖 Read More