Class-11-File Handling
Class-11-File Handling
Page : 1
File Handling
File handling is an important part of any web application. You often need to open and process a
file for different tasks. PHP has several functions for creating, reading, uploading, and editing
files.
readfile() Function
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows (the readfile()
function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read its contents.
File Open/Read/Close
Open File - fopen()
This function gives you more options than the readfile() function.
We will use the text file, "webdictionary.txt", which contains the following text.
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description
PHP Notes – File Handling. Page : 2
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if it
w
doesn't exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File pointer starts at
a
the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
Open a file for read/write. Erases the contents of the file or creates a new file if it
w+
doesn't exist. File pointer starts at the beginning of the file
Open a file for read/write. The existing data in file is preserved. File pointer starts at
a+
the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Read File - fread()
The fread() function reads from an open
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
Close File - fclose()
The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You don't
want an open file running around on your server taking up resources.
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
Read Single Line - fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next line.
Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
PHP Notes – File Handling. Page : 3
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "Pradeep P. K." and second contained "Manoj P. S.". After we
finished writing, we closed the file using the fclose() function.
If we open the "newfile.txt" file it would look like this:
Pradeep P. K.
Manoj P. S.
Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing
file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Old is Gold\n";
fwrite($myfile, $txt);
$txt = "Gold is precious\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we
just wrote is present:
Old is Gold
Gold is precious
File Upload
With PHP, it is easy to upload files to the server.
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types
gives an error message before setting $uploadOk to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Complete Upload File PHP Script
The complete "upload.php" file now looks like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
PHP Notes – File Handling. Page : 7