URLs and File Paths

Get the current URL

$url =
    'http' . (isset($_SERVER['HTTPS']) ? 's' : '' ) .
    '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

Get parts of a URL

$url = 'http://username:password@hostname:9090/path?arg=value#anchor';

echo parse_url($url, PHP_URL_SCHEME); // Returns "http"
echo parse_url($url, PHP_URL_USER);   // Returns "username"
echo parse_url($url, PHP_URL_PASS); // Returns "password"
echo parse_url($url, PHP_URL_HOST); // Returns "hostname"
echo parse_url($url, PHP_URL_PORT); // Returns ""
echo parse_url($url, PHP_URL_PATH); // Returns "/path"
echo parse_url($url, PHP_URL_QUERY); // Returns "arg=value"
echo parse_url($url, PHP_URL_FRAGMENT); // Returns "anchor"

// Get all the URL parts in an array.
$url_parts = parse_url($url);

Get the current file path

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

// Example:
// Both methods produce exactly the same result:
// string '/home/squale/developpement/tests/temp' (length=37)

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";