PHP - File System

Card Puncher Data Processing

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:

  • :lang:php:fs 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)





Discover More
Card Puncher Data Processing
Datacadamia - Data all the things

Computer science from a data perspective
Card Puncher Data Processing
PHP - File System

operation in php All files are read and becomes bytes (for a string/ text, by default in the ASCII character set). file_get_contents from an URL from the same directory than the script ...
Card Puncher Data Processing
Php - Regular expressions (Perl-compatible)

in Php are an implementation of Perl (PCRE) with the PCRE library (See ). Therefore, the syntax for patterns used in these functions closely resembles to Perl (PCRE) but not totally. See reference.pcre.pattern.differencesPerl...



Share this page:
Follow us:
Task Runner