PHP - File System

About

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).

Snippets

Read a file content

file_get_contents

  • from an URL
$homepage = file_get_contents('http://www.example.com/');
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);
}

where:

Get the file extension

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

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

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

Returns TRUE on success or FALSE on failure.

Get parent directory

dirname

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

were:

  • $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);

Powered by ComboStrap