QUIZGUM

Coding Class

Quizgum : directory function

directory function

Function to open a directory : opendir()
Function to close a directory : closedir()
Function to read a directory : readdir()

The parameters of opendir and closedir are directory paths.

Let's look at an example.

/htdocs/dir.php

  1. <?php
  2. echo "directory function example<br />";
  3.  
  4. $dir = '/Applications/';
  5. //$dir = "c:/windows/"; //if you use windows OS
  6.  
  7. if(is_dir($dir)){
  8. if($dirop = opendir($dir)){
  9. while(($filerd = readdir($dirop)) != false){
  10. echo " {$filerd} <br />";
  11. }
  12. echo "-------------------------------------- <br />";
  13. }
  14. } else {
  15. echo "{$dir} does not exist.<br />";
  16. }
  17. closedir($dirop);
  18. ?>

Result(for example MacOS)

php image

Result(for example windows)

php image php image

4line - Store the directory name in $dir.
7line - is_dir() is a function that determines whether a directory exists.
$dir is determined to be true and the following is done
8line - Use $dirop as a variable to open a directory.
$dirop = Opens a directory in opendir($dir) and outputs the folders and files in it while looping while(($filerd = readdir($dirop))! = false).

Finding and relocating directories getcwd(0, chdir()

Use getcwd() to find out where the current directory is, and then use chdir() to specify the path of the directory to change.

/htdocs/getcwd.php

  1. <?php
  2. echo "getcwd() , chdir() <br />";
  3. echo "current location <br />";
  4.  
  5. $path = getcwd();
  6.  
  7. echo "{$path} <br />";
  8. chdir("/Applications/");
  9. //chdir("c:/temp/"); //if you use windows OS
  10.  
  11. $path = getcwd();
  12.  
  13. echo "current location <br />";
  14. echo " $path <br />";
  15. ?>
php image