php get URL of current file directory

php get URL of current file directory

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Getting the Base URL for the Current File in PHP

Developers often confuse the filesystem path of a script with its accessible URL. While realpath(__DIR__) reliably returns the absolute directory on disk, such as /Applications/MAMP/htdocs/mysite/dir1/dir2/dir3, this information is useless to a web browser. To generate working relative links, you need the base URL: http://localhost:8888/dir1/dir2/dir3.

The challenge arises when a controller or entry point script (e.g., index.php) includes another file located deep within the directory structure (myfile.php). The included file needs to know its own position in the request hierarchy without hardcoding paths.

Why $_SERVER is Insufficient

A common first instinct is to rely on $_SERVER['SCRIPT_NAME'] or $_SERVER['PHP_SELF']. However, these variables are not always reliable for constructing base URLs.

SCRIPT_NAME contains the path relative to the document root. If your web server is configured with a specific virtual host setup or if you have multiple scripts in different directories, this value might be incomplete or incorrect depending on how the request was routed. Furthermore, PHP_SELF includes the filename, whereas you typically need the directory path to construct a clean base URL for linking.

Relying solely on $_SERVER['HTTP_HOST'] combined with SCRIPT_NAME works in simple scenarios but breaks down quickly when dealing with subdirectories or complex .htaccess rules. The solution must account for the script's actual location in the filesystem relative to the document root, then prepend the appropriate protocol and host.

Using basename to Strip the Filename

The most robust way to derive the base URL of the current file is to construct the full path first and then strip the filename itself. This approach mirrors how you would manually calculate a directory path.

You can combine dirname() with __FILE__ (or __DIR__) to get the absolute filesystem path, but you need the URL equivalent. Here is a pattern that constructs the base URL dynamically:

<?php

// Get the full path to the current file
$fullPath = __FILE__;

// Extract just the filename to remove it from the path
$filename = basename($fullPath);

// Remove the filename from the path to get the directory
$dirPath = dirname($fullPath);

// Prepend the scheme and host obtained from $_SERVER
// Note: Ensure you handle cases where these might be empty or undefined
$scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];

// Combine them. dirname() usually returns a path starting with '/' if called on __FILE__
// depending on the OS, but for URL construction we often need to ensure it is relative to root.
// If $dirPath starts with the document root (e.g., /htdocs/site/sub), 
// you might need to strip the physical root to leave only the virtual path.

// A safer approach often involves using SCRIPT_NAME directly if available,
// but if that fails due to routing quirks, we can reconstruct it:

$baseUrl = $scheme . '://' . $host . dirname($dirPath); // This logic varies based on exact setup

// Actually, the most direct way to get the base URL of the *current* script 
// is often just SCRIPT_NAME without the filename.
$baseName = dirname($_SERVER['SCRIPT_NAME']);

if (empty($baseName)) {
    $baseName = '/';
}

$finalBaseUrl = $scheme . '://' . $host . $baseName;

echo $finalBaseUrl; 
// Output: http://localhost:8888/dir1/dir2/dir3/

?>

In many standard setups, dirname($_SERVER['SCRIPT_NAME']) provides exactly what you need. It returns the directory portion of the script name relative to the root. If SCRIPT_NAME is /dir1/dir2/dir3/myfile.php, dirname() yields /dir1/dir2/dir3. Prepending $_SERVER['HTTP_HOST'] and the protocol gives you the correct base URL for generating links.

Handling Relative Links

Once you have established the base URL, constructing relative paths becomes trivial. If you are inside dir3 and want to link to a file in dir1, you can use standard relative path logic:

$baseUrl = dirname($_SERVER['SCRIPT_NAME']); // e.g., /dir1/dir2/dir3/

// To go up two levels from dir3 to dir1
$currentDir = $baseUrl; 
$targetDir = '/dir1'; 

// Or simply use a relative path string if you know the structure
$relativePath = '../..'; 

echo $baseUrl . $relativePath . '/target.php'; 

Frameworks and Alternatives

In modern Laravel applications, you rarely need to construct URLs manually from scratch. The url() helper or asset() function handles the protocol, host, and path resolution automatically, abstracting away the $_SERVER nuances. For example:

$url = url('dir1/dir2/dir3'); 

If you are building a custom application or working with legacy codebases where framework helpers aren't an option, mastering the relationship between SCRIPT_NAME and the filesystem path is essential for generating dynamic navigation menus and asset links without hardcoding paths.

Our network