Here is PHP code to:
1) Read / Scan any directory
2) Read any file
3) Write to any file
1) Read or Scan directory
Get all files and folders inside the directory.
Three ways are shown below.
a) Read/Scan directory using opendir() and readdir() function
$dir = "/var/www/test";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
print_r($files);
b) Read/Scan directory using scandir() function
$dir = '/var/www/test';
$files1 = scandir($dir);
$files2 = scandir($dir, 1); // sorting, 1=descending & 0=ascending
print_r($files1);
print_r($files2);
c) Read/Scan directory using glob() function
$path = "/var/www/test";
// get only folders
$directories = glob($path . '/*' , GLOB_ONLYDIR);
print_r($directories);
// get all files and folders
$allFileFolder = glob($path . '/*');
print_r($allFileFolder);
2) Read a file using fread() function
$filename = "/var/www/test/test.txt";
$handle = fopen($filename, "r"); // r = read mode, w = write mode, a = append mode
$contents = fread($handle, filesize($filename));
fclose($handle);
3) Write to file using fwrite()
$filename = 'test.txt';
$somecontent = "Hello there!";
// 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";
}
Thanks.