Handle a directory there are several functions in PHP language.
i. mkdir()
ii. opendir()
iii. readdir()
iv. scandir()
v. rmdir()
vi. closedir()
i. Create Directory
Want to create a new folder using PHP then use mkdir(). Only one argument is required the folder name or folder location where want to create the folder.
Example
1 2 3 | <?php mkdir('New Folder'); ?> |
ii. Open Directory
Using opendir() function can open a folder.Only one argument is required the folder path that is to be opened.
Example
1 2 3 4 | <?php opendir('C:\xampp\htdocs\MVT\Array\New Folder'); echo'Directory open'; ?> |
iii. Read Directory
readdir() is used to read any folder content. Return the all files and sub directory list of the specified folder (what want to read). One argument is required the folder path.
Example
1 2 3 4 5 6 | <?php $handle = opendir('C:\xampp\htdocs\MVT\Array'); while (false !== ($files = readdir($handle))) { echo "$files<BR>"; } ?> |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 | . .. 3wishes.txt array.php copy-flower.jpg file_create.php flower.jpg index1.php menu.php New folder new text file.txt newfile.txt picture.jpg |
iv.Scan Directory
sacndir() is same as readdir() but there are small difference. sacndir() return the all files and sub folder name as an array. One argument is required the folder path. No need to open folder in this case.
Example
1 2 3 4 5 6 | <?php $folderlocation = 'C:\xampp\htdocs\MVT\Array'; $allfiles = scandir($folderlocation); echo "<PRE>"; print_r($allfiles); echo " |
”;
?>
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | Array ( [0] => . [1] => .. [2] => 3wishes.txt [3] =>New folder [4] =>array.php [5] => copy-flower.jpg [6] =>file_create.php [7] => flower.jpg [8] => index1.php [9] =>menu.php [10] => new text file.txt [11] => newfile.txt [12] => picture.jpg ) |
v. Remove Directory
rmdir() function is used to remove or delete any empty folder from the specified location. If the folder is not empty then rmdir() is not work.
Example
1 2 3 | <?php rmdir('New Folder'); ?> |
vi. Close Directory
closedir() function is used to closed any directory.
Example
1 2 3 4 5 6 7 | <?php $handle = opendir('C:\xampp\htdocs\MVT\Array'); while (false !== ($files = readdir($handle))) { echo "$files<BR>"; } closedir($handle); ?> |