PHP image upload function, save in a dir and then return save image url

PHP image upload function, save in a dir and then return save image url

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

Stefan Bogdanescu

Founder & Senior Architect

Secure Image Uploads: Saving Files and Returning URLs

Building a file upload feature in PHP requires more than just moving a file from the client to the server. The code snippet you provided demonstrates the basic logic for validating MIME types, checking file sizes, and using move_uploaded_file() to persist data. However, relying on that specific implementation without addressing security headers or sanitization will leave your application vulnerable.

The primary issue with the provided function is how it handles the filename. Using $_FILES[$img]["name"] directly in the destination path creates an open redirect vulnerability and allows users to upload files into unexpected directories if they name their uploads ../../etc/passwd. You must sanitize the filename before using it as a filesystem path.

Sanitizing File Names and Paths

Before calling move_uploaded_file(), you need to strip any directory traversal attempts and ensure the file is stored in a predictable location. The standard approach involves extracting the base filename, removing its extension, and creating a unique identifier, usually based on a hash of the original filename or a random string.

Here is a robust implementation that addresses these security concerns:

function upload_img($img) {
    $uploadDir = __DIR__ . '/uploads';
    
    // Ensure the directory exists and is writable
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    } elseif (!is_writable($uploadDir)) {
        throw new Exception("Upload directory is not writable.");
    }

    $allowedTypes = ['image/gif', 'image/jpeg', 'image/png'];
    $maxSize = 2 * 1024 * 1024; // 2MB

    if (!isset($_FILES[$img]) || $_FILES[$img]['error'] !== UPLOAD_ERR_OK) {
        return false; 
    }

    $file = $_FILES[$img];

    if (in_array($file['type'], $allowedTypes, true) && $file['size'] <= $maxSize) {
        // Sanitize filename: remove path info and extension
        $originalName = basename($file['name']);
        $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        
        // Generate a unique filename to prevent collisions
        $uniqueFileName = uniqid() . '.' . $extension;
        $destinationPath = $uploadDir . '/' . $uniqueFileName;

        if (move_uploaded_file($file['tmp_name'], $destinationPath)) {
            // Return the relative URL, not the absolute filesystem path
            return '/uploads/' . $uniqueFileName; 
        }
    }

    return false;
}

Handling the Return Value in Your Database

In your original example, you called save_string_to_database( upload_img($_POST['photo']));. This works if your database column expects a simple string, but it is crucial to understand what that string represents.

The function should return a relative path (e.g., /uploads/photo123.jpg) rather than the full filesystem path (e.g., /var/www/html/themes/images/photo123.jpg). Storing the absolute filesystem path in your database makes it difficult to serve the image correctly across different environments (production vs. staging) and exposes internal directory structures. By returning a relative URL, your application can prepend the base URL of your domain when displaying the image in HTML:

<img src="https://yourdomain.com" .upload_img($_POST['photo'])">

Why the Original Code Failed

The reason the code from Stack Overflow did not work likely stems from two areas: missing directory creation and lack of error handling. The function assumes THEME_DIR."/images/" exists and is writable. If the directory does not exist, PHP throws a fatal error before the upload logic completes. Additionally, the original code checks MIME types against specific strings like image/gif. While this works for simple cases, attackers can sometimes spoof headers. For production applications, relying solely on file extension or header checking is risky; always verify the file content using the finfo_file() function or similar binary inspection methods if strict security is required.

Final Considerations

When implementing this in a modern framework like Laravel, you might use the Storage facade instead of handling raw filesystem paths, which handles symlinks and cloud storage abstractions automatically. However, for vanilla PHP scripts, ensuring the upload directory permissions are set to 0755 (or stricter) is mandatory so that web server processes can write files without creating security holes like world-writable directories.

Our network