How to Work with Files and Directories in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM


$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM


$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

PHP provides a range of functions to manipulate files and directories. Whether you’re reading data from a file, writing to it, or managing directories, PHP offers an array of commands to streamline these operations. In this article, we’ll explore how to work with files and directories in PHP, accompanied by practical command examples.

Opening a File

To open a file in PHP, you can use the fopen() function. This function takes two parameters – the filename and the mode (read, write, append, etc.).

$file = fopen("example.txt", "r");

Reading from a File

Once a file is open, you can read its content using fread(). The example below demonstrates how to read a file line by line.

$file = fopen("example.txt", "r");

while(!feof($file)) {
    $line = fgets($file);
    echo $line;


Writing to a File

To write to a file, you can use fwrite(). The following example illustrates how to open a file for writing and add content.

$file = fopen("example.txt", "w");
$content = "Hello, PHP!";
fwrite($file, $content);

Closing a File

It’s essential to close a file after performing operations on it. Use fclose() to close the file resource.

$file = fopen("example.txt", "r");
// Perform operations

Creating a Directory

Creating a directory in PHP is straightforward with mkdir(). The second parameter specifies permissions.

mkdir("new_directory", 0777);

Listing Files in a Directory

To get the list of files in a directory, use scandir(). The following example lists all files in a directory.

$files = scandir("directory_path");

foreach ($files as $file) {
    echo $file . "\n";

Checking if a Directory Exists

Before performing operations on a directory, it’s prudent to check if it exists using is_dir().

if (is_dir("directory_path")) {
    // Directory exists, perform operations
} else {
    // Directory does not exist

Deleting a Directory

Removing a directory can be done with rmdir(). Ensure the directory is empty or use additional checks to avoid accidental data loss.


Copying and Moving Files

PHP provides functions like copy() and rename() to duplicate or relocate files.

$source = "source_file.txt";
$destination = "destination_file.txt";

if (copy($source, $destination)) {
    echo "File copied successfully.";
} else {
    echo "Error copying file.";

Moving a File

$oldLocation = "old_location/file.txt";
$newLocation = "new_location/file.txt";

if (rename($oldLocation, $newLocation)) {
    echo "File moved successfully.";
} else {
    echo "Error moving file.";

File Deletion

Deleting files can be done using unlink(). Ensure that the file exists before attempting deletion.

$fileToDelete = "file_to_delete.txt";

if (file_exists($fileToDelete)) {
    echo "File deleted successfully.";
} else {
    echo "File not found.";

Handling File Uploads

PHP simplifies file uploads through the $_FILES superglobal. Here’s a basic example of handling file uploads:

    $targetDirectory = "uploads/";
    $targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "File uploaded successfully.";
    } else {
        echo "Error uploading file.";

Manipulating files and directories is a common requirement in web development. PHP provides a rich set of functions to perform these operations efficiently. Whether you’re dealing with file content, managing directories, or handling uploads, these commands empower you to build robust and dynamic applications.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.