Last active
June 28, 2019 14:07
-
-
Save Alexander-Pop/5f48dbf3e7c12af8fdcf99cb1bbe9826 to your computer and use it in GitHub Desktop.
PHP: Read Write File, Read Scan Directory #php #crud
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/*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"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment