How to Read / Write a File and Scan a Directory in PHP

In this blog, I am going to show you how to

  • Read / Scan any directory
  • Read a file
  • Write to a file

Read / Scan any Directory:

Here the code to get all the files and folders inside the directory.

We can use the following three ways to read any directory,

1) Read / Scan any directory using opendir() and readdir() function,

<?php 
$dir = '/var/www/html/myfolder';
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);
echo '<pre>';
    print_r($files);
echo '</pre>';

rsort($files);
echo '<pre>';
    print_r($files);
echo '</pre>';

2) Read / Scan any directory using scandir() function

<?php 
$dir = '/var/www/html/myfolder';

$files1 = scandir($dir);
echo '<pre>';
    print_r($files1);
echo '</pre>';

$files2 = scandir($dir, 1); // sorting: 0 = ascending & 1 = descending
echo '<pre>';
    print_r($files2);
echo '</pre>';

3) Read / Scan any directory using glob() function

<?php 
$dir = '/var/www/html/myfolder';

// get only folders
$directories = glob($path . '/*' , GLOB_ONLYDIR);
echo '<pre>';
    print_r($directories);
echo '</pre>';

// get all files and folders
$allFilesDirectories = glob($path . '/*');
echo '<pre>';
    print_r($allFilesDirectories);
echo '</pre>';

Read a File:

Here the code to read a file using fread() function

<?php 
$filename = 'file.txt';
$handle = fopen($filename, 'r'); // r = read mode, w = write mode, a = append mode
$contents = fread($handle, filesize($filename));
print_r($contents);
fclose($handle);

Write to a File:

Here the code to write to a file using fwrite()

<?php 
$filename = 'file.txt';
$somecontent = 'Hello World!';

// check if file exist and is writable
if (is_writable($filename)) {

    // opening file in append 'a' mode
    if (!$handle = fopen($filename, 'a')) {
        echo "Cannot open file '$filename'";
        exit;
    }

    // Write $somecontent to the opened file
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file '$filename'";
        exit;
    }

    echo "Success, wrote '$somecontent' to file '$filename'";
    fclose($handle);

} else {
    echo "The file '$filename' is not writable";
}

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *