How to display images from a folder using php - PHP

How to display images from a folder using php - PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Why Your PHP Image Gallery Returns 404 Errors

Encountering a 404 error when trying to display images from a local directory in PHP is a common frustration, especially when running on localhost. The code snippet provided checks for file existence, filters by extension, and attempts to output an <img> tag. However, the browser's inability to load the image suggests a disconnect between how the server constructs the URL and what the browser expects to receive.

The core issue usually lies in how scandir() behaves versus how PHP builds the absolute path for the src attribute. The function scandir() returns filenames relative to the directory you scanned, not absolute paths starting from your web root. In the provided code, $dir is set to /home/user/Pictures. While this looks like an absolute filesystem path, it is highly likely that your web server (like Apache or Nginx) serves files from a document root such as /var/www/html or htdocs, not /home/user.

When you echo the variable $dir directly into the src attribute, you are outputting a raw Linux filesystem path:
<img src="/home/user/Pictures/image.jpg" ... />

Most web servers do not serve files located in /home unless specifically configured to do so via .htaccess or virtual host settings. The browser attempts to fetch this URL from the live server, fails to find a resource at that absolute path, and returns a 404. Even if the file exists physically on your machine, it is invisible to the HTTP protocol unless the URL structure matches the web root.

Using realpath() for Consistency

To resolve this, you must ensure the path passed to the browser corresponds to what the web server actually serves. If you are generating URLs dynamically based on directory contents, relying on relative paths from the current script location is often safer than hardcoding absolute filesystem paths.

Consider replacing the hardcoded $dir with a path relative to your application's root or utilizing realpath() to normalize the path before outputting it. This ensures that regardless of where the script resides in the file system, the URL generated points to the correct location within the web root.

// Determine the base path relative to the web root
$baseDir = realpath(__DIR__ . '/../Pictures');

if (file_exists($baseDir) === false) {
    echo 'Directory not found!';
} else {
    $dir_contents = scandir($baseDir);

    foreach ($dir_contents as $file) {
        $file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));

        if ($file !== '.' && $file !== '..' && in_array($file_type, ['jpg', 'jpeg', 'png', 'gif'])) {
            // Construct the URL relative to the web root
            // Assuming the script is in /var/www/html and images are in /var/www/html/Pictures
            $imgSrc = str_replace('\\', '/', $baseDir) . '/' . $file;
            
            // If the image folder is inside the public folder, use a relative path:
            // $imgSrc = 'Pictures/' . $file; 
            
            echo '<img src="' . htmlspecialchars($imgSrc) . '" alt="' . htmlspecialchars($file) . '" />';
        }
    }
}

Security Considerations with Dynamic Images

While fixing the 404 error, it is crucial to address security implications inherent in dynamically generating image tags. The original code uses echo directly with concatenated strings from scandir(). If a user uploads a file named script.php into that folder, and your filter logic only checks extensions, you might inadvertently expose executable content if the extension check is bypassed or if you are serving files based on user input.

Always sanitize the filename before echoing it. The pathinfo() function is more robust than explode('.', $file) because it correctly handles filenames with multiple dots (e.g., image.tar.gz). Furthermore, using htmlspecialchars() prevents Cross-Site Scripting (XSS) vulnerabilities if a malicious file manages to slip through your extension filter and get renamed or uploaded.

The Role of Document Root Configuration

If you are still seeing 404 errors after adjusting the paths, verify your server configuration. In Apache, the mod_rewrite rules and the DocumentRoot directive determine which paths are accessible via HTTP. A path like /home/user/Pictures is a valid filesystem location but not necessarily a valid URL location unless explicitly mapped.

For production environments, consider using a dedicated public folder structure. If you are building a larger application, frameworks like Laravel handle this abstraction elegantly by providing helper methods to generate asset URLs that automatically account for the APP_BASE_PATH. For those managing custom PHP projects without a framework, maintaining a clear distinction between the filesystem path and the URL path is non-negotiable.

For more advanced asset management needs or if you are transitioning from raw PHP to a modern stack, exploring how Laravel handles asset loading in its public directory can offer valuable insights into secure and scalable image handling practices.

Our network