PHP - File System


File - File System (filesystem) operation in php

All files are read and becomes bytes (for a string/ text, by default in the ASCII character set).


Read a file content


  • from an URL
$homepage = file_get_contents('');
echo $homepage;
  • from the same directory than the script
$homepage = file_get_contents(dirname(__FILE__). '/homepage.html');
echo $homepage;

Create directory

The mode is mandatory.

if (!file_exists($dir)) {
        mkdir($dir, $mode = 0770, $recursive = true);


Get the file extension

$path_parts = pathinfo('/www/htdocs/inc/');

echo $path_parts['dirname'], "\n"; // directory
echo $path_parts['basename'], "\n"; // name.extension
echo $path_parts['extension'], "\n"; // extension
echo $path_parts['filename'], "\n"; // since PHP 5.2.0, name without extension

Check if path is relative of directory

if $dir is a base directory for $file (ie a relative path can be created) return true

strpos($file, $dir) === 0

Get file meta (Date,Time,Size,..)

stat - Gives file meta information

Copy a file

copy function

copy (__DIR__.'/resources/bootstrapLocal.json',__DIR__.'/../bootstrap/bootstrapLocal.json');

Delete a file


unlink ( __DIR__.'/../bootstrap/bootstrapLocal.json');

Returns TRUE on success or FALSE on failure.

Get parent directory


dirname(string $path, int $levels = 1): string


  • $path is a string path.
  • $levels is the number of parent directories to go up. (ie
    • $levels=1 = parent
    • $levels=2 = grand parent

Get children directory

With the glob function that takes as input a globbing expression

$childrenDirectories = glob($directory . DIRECTORY_SEPARATOR. '*' , GLOB_ONLYDIR);

File Root Detection

From the doc: dirname, detection of the file system root.

dirname('.');    // Will return '.'.
dirname('/');    // Will return `\` on Windows and '/' on *nix systems.
dirname('\\');   // Will return `\` on Windows and '.' on *nix systems.
dirname('C:\\'); // Will return 'C:\' on Windows and '.' on *nix systems.

The pattern is then

$isRoot = preg_match("/^\.|\\\\|[a-z]:\\\\$/i", $path)

Powered by ComboStrap