Files

Include a file

  • Include local files using the include() or require() methods. Both methods are the same except for the fact that require() produces a fatal error if it fails while include() only produces a warning.
include('../my_file.php');

Get the current file path

// Get the absolute path to the directory containing the current working file.
$dir_path = __DIR__; // Recommended fastest way, but only available for PHP >= 5.3.
$dir_path = dirname(__FILE__);

Get parts of a file path

$file_path = '/home/mydir/myfile.pdf';

// Get all the path parts in an array.
$file_path_parts = pathinfo( $file_path );

// Get each part separately
echo pathinfo( $file_path, PATHINFO_DIRNAME); // Returns "/home/mydir"
echo pathinfo( $file_path, PATHINFO_BASENAME); // Returns "myfile.pdf"
echo pathinfo( $file_path, PATHINFO_EXTENSION); // Returns "pdf"
echo pathinfo( $file_path, PATHINFO_FILENAME); // Returns "myfile"

Get a file extension

This is faster than using pathinfo() or getting the value from array if you just need the ext.

$ext = substr(strrchr($filename, "."), 1);

Get the headers of a remote file

Get the headers from a file hosted at a remote server without downloading the whole file.
Headers contain content-type and file size info.

$media_file_headers = array_change_key_case(get_headers($file_url, TRUE));

Check if a local file exists

$filename = $_SERVER['DOCUMENT_ROOT'] . 'images/myImage.png';

if (file_exists($filename)) {
     echo "The file $filename exists";
} else {
     echo "The file $filename does not exist";
}