Chapter 3-Working With Files and Directories in PHP
Chapter 3-Working With Files and Directories in PHP
The include() and require() statements allow you to include the code contained in a PHP file
within another PHP file. Including a file produces the same result as copying the script from the
file specified and pasted into the location where it is called.
You can save a lot of time and work through including files — Just store a block of code in a
separate file and include it wherever you want using the include() and require() statements
instead of typing the entire block of code multiple times. A typical example is including the
header, footer and menu file within all the pages of a website.
The basic syntax of the include() and require() statement can be given with:
Tip: Like the print and echo statements, you can omit the parentheses while using the include
and require statements as demonstrated above.
The following example will show you how to include the common header, footer and menu
codes which are stored in separate 'header.php', 'footer.php' and 'menu.php' files respectively,
within all the pages of your website. Using this technique you can update all pages of the website
at once by making the changes to just one file; this saves a lot of repetitive work.
<!DOCTYPE html>
<html lang="en">
<head>
<title> files to be included </title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>
1 of page 17
Difference between include and require Statements
You might be thinking if we can include files using the include() statement then why we need
require(). Typically the require() statement operates like include().
The only difference is — the include() statement will only generate a PHP warning but allow
script execution to continue if the file to be included can't be found, whereas the require()
statement will generate a fatal error and stops the script execution.
Tip: It is recommended to use the require() statement if you're including the library files or
files containing the functions and configuration variables that are essential for running your
application, such as database configuration file.
If you accidentally include the same file (typically functions or classes files) more than one time
within your code using the include or require statements, it may cause conflicts. To prevent
this situation, PHP provides include_once and require_once statements. These statements
behave in the same way as include and require statements with one exception.
The include_once and require_once statements will only include the file once even if asked to
include it a second time i.e. if the specified file has already been included in a previous
statement, the file is not included again. To better understand how it works, let's check out an
example. Suppose we've a 'my_functions.php' file with the following code:
<?php
function multiplySelf($var){
$var *= $var; // multiply variable by itself
echo $var;
}
?>
Here's is the PHP script within which we've included the 'my_functions.php' file.
2 of page 17
<?php
// Including file
require "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
When you run the above script, you will see the error message something like this: "Fatal error:
Cannot redeclare multiplySelf()". This occurs because the 'my_functions.php' included twice,
this means the function multiplySelf() is defined twice, which caused PHP to stop script
execution and generate fatal error. Now rewrite the above example with require_once.
<?php
// Including file
require_once "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
As you can see, by using require_once instead of require, the script works as we expected.
3 of page 17
PHP File System
In this section you will learn how to create, access (or read) and manipulate files dynamically
using the PHP's file system functions.
Since PHP is a server side programming language, it allows you to work with files and
directories stored on the web server. In this section you will learn how to create, access, and
manipulate files on your web server using the PHP file system functions.
To work with a file you first need to open the file. The PHP fopen() function is used to open a
file. The basic syntax of this function can be given with:
fopen(filename, mode)
The first parameter passed to fopen() specifies the name of the file you want to open, and the
second parameter specifies in which mode the file should be opened. For example:
<?php
$handle = fopen("data.txt", "r");
?>
4 of page 17
If you try to open a file that doesn't exist, PHP will generate a warning message. So, to avoid
these error messages you should always implement a simple check whether a file or directory
exists or not before trying to access it, with the PHP file_exists() function.
<?php
$file = "data.txt";
Tip: Operations on files and directories are prone to errors. So it's a good practice to implement
some form of error checking so that if an error occurs your script will handle the error gracefully.
See the section on PHP error handling.
Once you've finished working with a file, it needs to be closed. The fclose() function is used to
close the file, as shown in the following example:
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
/* Some code to be executed */
fclose($handle); // Closing the file handle
} else{
echo "ERROR: File does not exist.";
}
?>
Note: Although PHP automatically closes all open files when script terminates, but it's a good
practice to close a file after performing all the operations.
Now that you have understood how to open and close files. In the following section you will
learn how to read data from a file. PHP has several functions for reading data from a file. You
can read from just one character to the entire file with a single operation.
5 of page 17
Reading Fixed Number of Characters
The fread() function can be used to read a specified number of characters from a file. The basic
syntax of this function can be given with.
This function takes two parameter — A file handle and the number of bytes to read. The
following example reads 20 bytes from the "data.txt" file including spaces. Let's suppose the file
"data.txt" contains a paragraph of text "The quick brown fox jumps over the lazy dog."
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
$content = fread($handle, "20"); // Read fixed number of bytes from the file
fclose($handle); // Closing the file handle
echo $content; // Display the file content
} else{
echo "ERROR: File does not exist."; }
?>
The fread() function can be used in conjugation with the filesize() function to read the
entire file at once. The filesize() function returns the size of the file in bytes.
<?php
$file = "data.txt";
6 of page 17
?>
The easiest way to read the entire contents of a file in PHP is with the readfile() function. This
function allows you to read the contents of a file without needing to open it. The following
example will generate the same output as above example:
<?php
$file = "data.txt";
Another way to read the whole contents of a file without needing to open it is with the
file_get_contents() function. This function accepts the name and path to a file, and reads the
entire file into a string variable. Here's an example:
<?php
$file = "data.txt";
One more method of reading the whole data from a file is the PHP's file() function. It does a
similar job to file_get_contents() function, but it returns the file contents as an array of lines,
rather than a single string. Each element of the returned array corresponds to a line in the file.
7 of page 17
To process the file data, you need to iterate over the array using a foreach loop. Here's an
example, which reads a file into an array and then displays it using the loop:
<?php
$file = "data.txt";
Similarly, you can write data to a file or append to an existing file using the PHP fwrite()
function. The basic syntax of this function can be given with:
The fwrite() function takes two parameter — A file handle and the string of data that is to be
written, as demonstrated in the following example:
<?php
$file = "note.txt";
In the above example, if the "note.txt" file doesn't exist PHP will automatically create it and
write the data. But, if the "note.txt" file already exist, PHP will erase the contents of this file, if it
has any, before writing the new data, however if you just want to append the file and preserve
existing contents just use the mode a instead of w in the above example.
8 of page 17
An alternative way is using the file_put_contents() function. It is counterpart of
file_get_contents() function and provides an easy method of writing the data to a file
without needing to open it. This function accepts the name and path to a file together with the
data to be written to the file. Here's an example:
<?php
$file = "note.txt";
If the file specified in the file_put_contents() function already exists, PHP will overwrite it
by default. If you would like to preserve the file's contents you can pass the special FILE_APPEND
flag as a third parameter to the file_put_contents() function. It will simply append the new
data to the file instead of overwitting it. Here's an example:
<?php
$file = "note.txt";
// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";
// Write data to the file
file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the
file.");
echo "Data written to the file successfully.";
?>
You can rename a file or directory using the PHP's rename() function, like this:
<?php
$file = "file.txt";
9 of page 17
You can delete files or directories using the PHP's unlink() function, like this:
<?php
$file = "note.txt";
The following table provides the overview of some other useful PHP filesystem functions that
can be used for reading and writing the files dynamically.
Function Description
fgetc() Reads a single character at a time.
fgets() Reads a single line at a time.
fgetcsv() Reads a line of comma-separated values.
filetype() Returns the type of the file.
feof() Checks whether the end of the file has been reached.
is_file() Checks whether the file is a regular file.
is_dir() Checks whether the file is a directory.
is_executable() Checks whether the file is executable.
realpath() Returns canonicalized absolute pathname.
rmdir() Removes an empty directory.
Please check out the PHP filesystem reference for other useful PHP filesystem functions.
In this section you will learn how to process directories or folders using PHP.
In the previous section you've learned how to work with files in PHP. Similarly, PHP also allows
you to work with directories on the file system, for example, you can open a directory and read
its contents, create or delete a directory, list all files in the directory, and so on.
10 of page 17
You can create a new and empty directory by calling the PHP mkdir() function with the path
and name of the directory to be created, as shown in the example below:
<?php
// The directory path
$dir = "testdir";
To make the mkdir() function work, the parent directories in the directory path parameter has to
exist already, for example, if you specify the directory path as testdir/subdir than the
testdir has to exist otherwise PHP will generate an error.
You can copy a file from one location to another by calling PHP copy() function with the file's
source and destination paths as arguments. If the destination file already exists it'll be
overwritten. Here's an example which creates a copy of "example.txt" file inside backup folder.
<?php
// Source file path
$file = "example.txt";
To make this example work, the target directory which is backup and the source file i.e.
"example.txt" has to exist already; otherwise PHP will generate an error.
11 of page 17
Listing All Files in a Directory
You can use the PHP scandir() function to list files and directories inside the specified path.
Now we're going to create a custom function that will recursively list all files in a directory using
PHP. This script will be helpful if you're working with deeply nested directory structure.
<?php
// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Scan the files in this directory
$result = scandir($path);
While working on directory and file structure, sometimes you might need to find out certain
types of files within the directory, for example, listing only .text or .png files, etc. You can do
this easily with the PHP glob() function, which matches files based on the pattern.
The PHP code in the following example will search the documents directory and list all the files
with .text extension. It will not search the subdirectories.
<?php
/* Search the directory and loop through
12 of page 17
returned array containing the matched files */
foreach(glob("documents/*.txt") as $file){
echo basename($file) . " (size: " . filesize($file) . " bytes)" . "<br>";
}
?>
The glob() function can also be used to find all the files within a directory or its subdirectories.
The function defined in the following example will recursively list all files within a directory,
just like we've done in previous example with the scandir() function.
<?php
// Define a function to output files in a directory
function outputFiles($path){
// Check directory exists or not
if(file_exists($path) && is_dir($path)){
// Search the files in this directory
$files = glob($path ."/*");
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$file")){
// Display only filename
echo basename($file) . "<br>";
} else if(is_dir("$file")){
// Recursively call the function if directories found
outputFiles("$file");
}
}
} else{
echo "ERROR: No such file found in the directory.";
}
} else {
echo "ERROR: The directory does not exist.";
}
}
In this section you'll learn how to upload a file to the remote web server with PHP.
In this section we will learn how to upload files on remote server using a Simple HTML form
and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office
documents, PDFs, as well as executables files and a wide range of other file types.
13 of page 17
Step 1: Creating an HTML form to upload the file
The following example will create a simple HTML form that can be used to upload files.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="upload-manager.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed
to a max size of 5 MB.</p>
</form> </body>
</html>
Note: In addition to a file-select field the upload form must use the HTTP post method and must
contain an enctype="multipart/form-data" attribute. This attribute ensures that the form data
is encoded as mulitpart MIME data — which is required for uploading the large quantities of
binary data such as image, audio, video, etc.
Here's the complete code of our "upload-manager.php" file. It will store the uploaded file in a
"upload" folder on permanent basis as well as implement some basic security check like file type
and file size to ensure that users upload the correct file type and within the allowed limit.
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif"
=> "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
14 of page 17
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";}
} else{
echo "Error: There was a problem uploading your file. Please try again."; }
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
Note: The above script prevents uploading a file with the same name as an existing file in the
same folder. However, if you want to allow this just prepend the file name with a random string
or timestamp, like $filename = time() . '_' . $_FILES["photo"]["name"];
You might be wondering what this code was all about. Well, let's go through each part of this
example code one by one for a better understanding of this process.
Explanation of Code
Once the form is submitted information about the uploaded file can be accessed via PHP
superglobal array called $_FILES. For example, our upload form contains a file select field called
photo (i.e. name="photo"), if any user uploaded a file using this field, we can obtains its details
like the name, type, size, temporary name or any error occurred while attempting the upload via
the $_FILES["photo"] associative array, like this:
$_FILES["photo"]["name"] — This array value specifies the original name of the file,
including the file extension. It doesn't include the file path.
$_FILES["photo"]["type"] — This array value specifies the MIME type of the file.
$_FILES["photo"]["size"] — This array value specifies the file size, in bytes.
$_FILES["photo"]["tmp_name"] — This array value specifies the temporary name
including full path that is assigned to the file once it has been uploaded to the server.
$_FILES["photo"]["error"] — This array value specifies error or status code associated
with the file upload, e.g. it will be 0, if there is no error.
The PHP code in the following example will simply display the details of the uploaded file and
stores it in a temporary directory on the web server.
<?php
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
echo "File Name: " . $_FILES["photo"]["name"] . "<br>";
echo "File Type: " . $_FILES["photo"]["type"] . "<br>";
echo "File Size: " . ($_FILES["photo"]["size"] / 1024) . " KB<br>";
15 of page 17
echo "Stored in: " . $_FILES["photo"]["tmp_name"];
}
?>
Tip: Once a file has been successfully uploaded, it is automatically stored in a temporary
directory on the server. To store this file on a permanent basis, you need to move it from the
temporary directory to a permanent location using the PHP's move_uploaded_file() function.
16 of page 17
PHP File Download
In this section you will learn how to force download a file using PHP.
Normally, you don't necessarily need to use any server side scripting language like PHP to
download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public
accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click
on the link, browser will automatically downloads that file.
Clicking a link that points to a PDF or an Image file will not cause it to download to your hard
drive directly. It will only open the file in your browser. Further you can save it to your hard
drive. However, zip and exe files are downloaded automatically to the hard drive by default.
You can force images or other kind of files to download directly to the user's hard drive using the
PHP readfile() function. Here we're going to create a simple image gallery that allows users to
download the image files from the browser with a single mouse click.
Let's create a file named "image-gallery.php" and place the following code inside it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
.img-box{
display: inline-block;
text-align: center;
margin: 0 15px;
}
</style>
</head>
<body>
<?php
// Array containing sample image file names
$images = array("kites.jpg", "balloons.jpg");
17 of page 17
echo '<img src="images/' . $image . '" width="200" alt="' .
pathinfo($image, PATHINFO_FILENAME) .'">';
echo '<p><a href="download.php?file=' . urlencode($image) .
'">Download</a></p>';
echo '</div>';
}
?>
</body>
</html>
If you see the above example code carefully, you'll find the download link pints to a
"download.php" file, the URL also contains image file name as a query string. Also, we've used
PHP urlencode() function to encode the image file names so that it can be safely passed as
URL parameter, because file names may contain URL unsafe characters.
Here's the complete code of "download.php" file, which force image download.
<?php
if(isset($_REQUEST["file"])){
// Get parameters
$file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
$filepath = "images/" . $file;
// Process download
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
exit;
}
}
?>
Similarly, you can force download other files formats like word doc, pdf files, etc.
18 of page 17