Exploring Folders

category: Advanced
Created by: Dr.Ferrous

Exploring Folders

category: Advanced
Created by: Dr.Ferrous
twitter google+ facebook pin 

PHP has functions that can also open directories (folders) and explore their contents, or create new folders.

Creating folders with PHP

To create a folder with PHP, use the mkdir() function. Returns TRUE on success or FALSE on failure.

"pathname " is the path and name of the new directory.
- "mode" sets the CHMOD permissions. It is optional (0777 by default).

This code attempt to create a folder named "newdir" in the "files" directory, with 0755 CHMOD permissions, and output a message on success or failure. PHP must have write permissions in the "files" directory.

Reading a directory content

You can read the content of a directory with one of the fallowing functions:

  • scandir('dir_path') - Returns an array of files and directories inside the "dir_path" (sorted in alphabetical ascending order), or FALSE on failure.
  • readdir($dir_handle) - Returns the filename of the next file from the folder, or False. The filenames are returned in the order in which they are stored by the filesystem.
    - "$dir_handle" is a handle resource opened with opendir()


"./" indicates the root directory of the Web site (www or htdocs). So, the "files" folder is located in the Web site root folder.
"opendir()" opens a directory and return a reference to it; "closedir()" closes an opened folder (similar with "fopen()" and "fclose()" for files).

Another way to Inspect the contents of a folder is with the DirectoryIterator class.

Get information about a file path

An useful PHP function to get info about a file path is pathinfo(). It returns an associative Array with the fallowing elements (keys):

  • dirname - parent directory's path. The same as dirname() function
  • basename - the base name of the given path. The same as basename() function
  • extension (if any) - the extension of the base name (if exists)
  • filename - the name of file, without extension


Other useful functions for file (folder) system

  • getcwd() - Gets the current working directory
  • parse_url($url) - parses a URL and returns an associative array containing the fallowing items (keys), with components of the URL:
    • "scheme" (e.g. http), "host", "port", "user", "pass", "path", "query" (after the question mark ?), "fragment" (after the hashmark #)


  • disk_free_space($dir) - returns the free space, in bytes, of the specified directory
  • is_dir('dir') - returns TRUE if the "dir" exists
  • is_file('file') - returns TRUE if "file" is a regular file
  • is_readable('filename') - returns TRUE if the file or directory specified by "filename" exists and is readable
  • is_writable('filename') - returns TRUE if the file or directory specified by "filename" exists and is writable