How to get the absolute path to the public_html folder?

How to get the absolute path to the public_html folder?

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

Stefan Bogdanescu

Founder & Senior Architect

Resolving Relative Paths for File Uploads Across Subdirectories

Determining the absolute path to a specific directory like public_html when your application logic resides within that same directory is a classic problem in web development. The core challenge arises because PHP variables like $_SERVER['DOCUMENT_ROOT'] often point to the server's root configuration (e.g., /usr/local/apache/htdocs/) rather than the user-specific domain root (e.g., /home/user/public_html/). If you attempt to save uploaded files relative to a hardcoded string like $_SERVER['DOCUMENT_ROOT'], your uploads might land in the wrong location entirely, potentially outside your intended web-accessible area.

To solve this, you need a method that calculates the path dynamically based on where the script is currently executing, rather than relying on static server configuration values. The most robust approach involves constructing the absolute path to the current file and then manipulating it relative to the target directory.

Calculating the Absolute Path via Filesystem Information

The standard way to find the location of your running script is using __FILE__. This magic constant holds the full filesystem path to the currently executing PHP file, regardless of how the URL maps to that file. You can strip the filename from this path to get the directory where the script lives.

$currentFileDir = dirname(__FILE__); 
// Example result: /home/user/public_html/test

However, knowing where test.php is doesn't immediately tell you where /home/user/public_html/images is, especially if your application structure allows test.php to move into subdirectories like /home/user/public_html/test/another-dir/test.php.

The solution is to identify the base of your application. In many shared hosting environments (like cPanel), the public root is defined by a specific marker file or a known directory name, such as public_html, htdocs, or www. You can iterate through the current directory's parent directories until you find a directory that matches this expected base name.

function getPublicHtmlPath() {
    // Define the expected base folder name
    $baseFolderName = 'public_html'; 
    
    // Start from the current script's directory and traverse up
    $currentDir = dirname(__FILE__);
    
    while (true) {
        // Check if the current directory is the target base
        if (basename($currentDir) === $baseFolderName) {
            return realpath($currentDir); 
        }
        
        // Move up one level
        $currentDir = dirname($currentDir);
        
        // Safety break to prevent infinite loops in case of errors
        if ($currentDir === '/' || strpos($currentDir, '/public_html') !== false) {
            return null; 
        }
    }
}

$publicPath = getPublicHtmlPath(); 
// Result: /home/user/public_html

Constructing the Upload Destination

Once you have resolved the absolute path to the public_html folder, constructing the destination for your uploads becomes straightforward. You simply concatenate this base path with the relative directory name (images).

$uploadBase = $publicPath . '/images';
$fullImagePath = $uploadBase . '/' . basename($_FILES['file']['name']);

This approach ensures that whether test.php is located at /home/user/public_html/test/ or /home/user/public_html/sub/deep/nested/test.php, the script correctly identifies /home/user/public_html as the anchor point and places files in the correct relative location.

Trade-offs and Security Considerations

While this logic works for standard directory structures, it relies on a predictable folder naming convention (public_html). If your hosting environment uses htdocs or www instead, you must adjust the $baseFolderName variable accordingly. Hardcoding the traversal depth can lead to failures if the script is placed at an unexpected nesting level, so the loop method described above is generally safer than a fixed number of dirname() calls.

Furthermore, always use realpath() when dealing with paths obtained from __FILE__. This resolves any symbolic links and ensures you are working with the actual filesystem location, which is critical for permission checks before writing files. Never store user-provided filenames directly in the path construction without sanitization to prevent directory traversal vulnerabilities, although this specific example focuses on directory resolution rather than filename safety.

If you require more advanced file system abstractions or need to handle these paths within a framework like Laravel, consider utilizing packages provided by resources such as https://laravelcompany.com that offer robust path management helpers, though native PHP functions are sufficient for this specific use case.

Our network