PHP File Handling

File handling is an important part of any web application. Here I discuss this topic by php. This article is based on PHP official Filesystem Functions.

The first step you can try to manipulate files with PHP, you can use readfile() function.

readfile('fileName.ext');

Here you get to read and count the characters of a file. Suppose you have a file named ** myfile.txt, and here you write Hello Worlds. After executing readfile('myfile.txt');, you get an output Hello Worlds12. Here 12 is the count of characters.

File Open, Read, and Close

$myfile =  fopen("myfile.txt", "r+") or die("Unable to open file!");

echo fread($myfile, filesize("myfile.txt"));

fclose($myfile);

When you want to something to do with a file you need to open it first, then read it, and then close it. The ** fopen(), function helps to open your file. 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. file May be opened in one of the following modes:

ModesDescription
rOpen a file for read only. The file pointer starts at the beginning of the file.
wOpen a file for writing only. Erase the contents of the file or create a new file if it doesn't exist. The file pointer starts at the beginning of the file.
aOpen a file for writing only. The existing data in a file is preserved. The file pointer starts at the end of the file. Creates a new file if the file doesn't exist.
xCreates a new file for writing only. Returns FALSE and an error if the file already exists.
r+Open a file for read/write. The file pointer starts at the beginning of the file.
w+Open a file for read/write. Erase the contents of the file or create a new file if it doesn't exist. The file pointer starts at the beginning of the file.
a+Open a file for read/write. The existing data in the file is preserved. The file pointer starts at 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 the file already exists.

Now, next line we see fread($myfile, filesize("myfile.txt")) , By fread() function read opened file. 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. Actually, filesize("myfile.txt") returns the number of characters of a file.

The last one makes files close. By fclose($myfile); function close file after complete manipulating. This is good coding practice. If you do not close the file, it's running around on your server taking up resources!

PHP Filesystem

In the below example, I discuss some important built-in functions for the PHP file system.

  1. basename() - It returns the file name from the path.

     $path = "/learning/index.php";
    
     //Show filename
     echo basename($path);
     // Output -> index.php
    
     //Show filename, but cut off file extension for ".php" files
     echo basename($path,".php");
     // Output -> index
    
  2. clearstatcache(): It clears the file status cache.

  3. copy() - This function copies a file.

     echo copy("index.php", "newIndex.php");
     // First parameter is Specifies the path to the file to copy from. 
     /* 
     * and second one is Specifies the path to the file to copy to.
     * If file already exists, it will be overwritten.
     */
    
  4. delete()/unlink(): It's deleting a file.

     echo unlink("newIndex.php");
    
  5. dirname(): This function returns the path of the parent directory.

     echo dirname("c:/xampp/htdocs/index.php");
     // Return: c:/xampp/htdocs
     /*
     * It's have a default parameter 1. If you applied 2 then,
     * echo dirname("c:/xampp/htdocs/index.php", 2);
     * Output: c:/xampp
     */
    
  6. disk_free_space()/diskfreespace() - returns the free space, in bytes, of the specified filesystem or disk.

  7. disk_total_space() - returns the total size, in bytes, of the specified filesystem or disk.

     echo "Disk free space: " . disk_free_space("C:");
     // Returns your c drive free space.
     echo "Disk free space: " . disk_total_space("C:");
     // Returns your c drive total space.
     // You can convert it bytes to gibibyte(GiB) to see you disk space.
    
  8. feof() function is used to check if the end of a file has been reached.

     <?php
     // Open a file for reading
     $filename = 'example.txt';
     $file = fopen($filename, 'r');
    
     // Check if the file is successfully opened
     if ($file) {
         // Read the file line by line until the end
         while (!feof($file)) {
             // Read a line from the file
             $line = fgets($file);
    
             // Display the line
             echo $line;
         }
    
         // Close the file
         fclose($file);
     } else {
         // Display an error message if the file cannot be opened
         echo "Unable to open file: $filename";
     }
    
     ?>
     // Run this code on your machine with a paragraph text.
    
  9. fgets() - returns a line from an open file.

     $file = fopen("example.txt","r");
    
     while(! feof($file))
      {
       echo fgets($file). "<br />";
      }
    
     fclose($file);
    
  10. file() - reads a file into an array. There are some associates function with file():

    file_exists(path) - // function checks whether a file or directory exists.
    file_get_contents("index.php") - // reads a file into a string.
    fileatime() - // returns the last access time of the specified file.
    filectime() - // function returns the last time a file was changed.(inode/regular changes);
    // Inode changes is when permissions, owner, group or other metadata is changed.
    filemtime() - // function to return the last time the file content was changed.
    filesize() - // Return file size in bytes
    filetype(); - // return type of file.
    /*
    # Possible return values:
    * fifo
    * char
    * dir
    * block
    * link
    * file
    * socket
    * unknown
    */
    
  11. is_dir() - function check your image directory. When you try to upload your files in a folder, this function checks if is it a folder or not.

    $file = "./assets";
    if (is_dir($file)) {
        echo ("$file is a directory");
    } else {
        echo ("$file is not a directory");
    }
    
  12. is_executable() - function checks whether the specified filename is executable.

    $file = "index.php";
    if(is_executable($file)) {
      echo ("$file is executable");
    } else {
      echo ("$file is not executable");
    }
    

    Here are some similar functions that can check specific executions:

    * is_file() // function checks whether the specified filename is a regular file.
    * is_link() // function checks whether the specified filename is a symbolic link.
    * is_readable() // function checks whether the specified filename is readable.
    * is_uploaded_file() // function checks whether the specified file is uploaded via HTTP POST.
    * is_writable()/is_writeable() // function checks whether the specified filename is writable.
    
  13. move_uploaded_file() function moves an uploaded file to a new destination. This function only works on files uploaded via PHP's HTTP POST upload mechanism.

  14. realpath() - function returns the absolute(full path) pathname.

    echo realpath("./function.txt");
    // returns: C:\xampp\htdocs\php\PHP\Study\Advance\function.txt
    
  15. rename() - function renames a file or directory.

    rename(oldName, newName, context);
    // Directory remane
    rename("./images","./assets");
    // 3rd parameter Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream.
    
  16. rmdir() - function removes an empty directory.

    // Removed assets folder
    rmdir("./assets");
    // After removed
    $path = "./assets";
    if(!rmdir($path)) {
      echo ("Could not remove $path");
    }
    
  17. stat() - Function returns details information about a file.

    print_r(stat("./function.txt"));
    // return array value like this: 
    Array ( 
    [0] => 2964826074 
    [1] => 2814749767495685 
    [2] => 33206 
    [3] => 1 
    [4] => 0 
    [5] => 0 
    [6] => 0 
    [7] => 24 
    [8] => 1705242450 
    [9] => 1705035795 
    [10] => 1704956648 
    [11] => -1 
    [12] => -1 
    [dev] => 2964826074 
    [ino] => 2814749767495685 
    [mode] => 33206 
    [nlink] => 1 
    [uid] => 0 
    [gid] => 0 
    [rdev] => 0 
    [size] => 24 
    [atime] => 1705242450 
    [mtime] => 1705035795 
    [ctime] => 1704956648 
    [blksize] => -1 
    [blocks] => -1 
    )
    // Technical Details
    /*
    [0] or [dev] - Device number
    [1] or [ino] - Inode number
    [2] or [mode] - Inode protection mode
    [3] or [nlink] - Number of links
    [4] or [uid] - User ID of owner
    [5] or [gid] - Group ID of owner
    [6] or [rdev] - Inode device type
    [7] or [size] - Size in bytes
    [8] or [atime] - Last access (as Unix timestamp)
    [9] or [mtime] - Last modified (as Unix timestamp)
    [10] or [ctime] - Last inode change (as Unix timestamp)
    [11] or [blksize] - Blocksize of filesystem IO (if supported)
    [12] or [blocks] - Number of blocks allocated
    */
    // It returns an E_WARNING on failure
    
  18. unlink() - function deletes a file.

    unlink("test.txt");
    // file will be deleted.
    

The filesystem functions are part of the PHP core. In the above, I try to show important filesystem built-in functions. Hope this helps you. Happy learning!

0
Subscribe to my newsletter

Read articles from Md. Moinul Hossain directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Md. Moinul Hossain
Md. Moinul Hossain

A Passionate web Application developer and DevOps enthusiast from Bangladesh.