Creating a thumbnail from an uploaded image

Creating a thumbnail from an uploaded image

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

Stefan Bogdanescu

Founder & Senior Architect

Handling Image Uploads: Scaling from Single File to Generated Thumbnails

Handling user-uploaded images requires a shift in mindset from simply storing files to managing data assets. The goal isn't just to accept a file; it is to validate, transform, and store both the original asset and derived versions like thumbnails without compromising performance or database integrity.

In the scenario described, the user wants to upload a profile picture while simultaneously generating a smaller thumbnail to prevent layout issues, storing both in their respective database columns (user_pic as longblob and user_pic_small as longblob). The current approach using raw PHP functions like addslashes and file_get_contents on the uploaded temporary file presents several architectural risks.

The primary concern with the existing implementation is how the image data is being processed before storage. Reading the entire file into memory with file_get_contents() works for small images, but it bypasses the built-in safety mechanisms of PHP's GD or Imagick libraries. More critically, wrapping the binary content in single quotes within a SQL query and escaping it with addslashes is a recipe for SQL injection if the input isn't perfectly controlled, and it makes debugging impossible because you are treating binary data as a string literal.

A robust solution involves separating the ingestion logic from the storage logic. Instead of manually constructing a massive SQL string, you should leverage prepared statements. This ensures that even if the binary data contains characters that look like quotes or semicolons, they are treated purely as part of the image file, not as SQL commands.

Here is a refined approach using modern PHP practices to handle the upload, generation, and storage:

// media.profileimage.upload.php

if (isset($_FILES['image_data']) && $_FILES['image_data']['error'] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES['image_data']['tmp_name'];
    $fileSize = filesize($tmpName);
    $fileType = $_FILES['image_data']['type'];

    // Basic validation before processing
    if ($fileSize > 5 * 1024 * 1024 || !in_array($fileType, ['image/jpeg', 'image/png'])) {
        die('Invalid file size or type.');
    }

    $targetDir = '/path/to/uploads/';
    $newFileName = uniqid() . '.' . pathinfo($tmpName, PATHINFO_EXTENSION);
    $originalPath = $targetDir . $newFileName;

    // Move the original file to a safe location first
    if (!move_uploaded_file($tmpName, $originalPath)) {
        die('Failed to move uploaded file.');
    }

    // Load image using GD library for processing
    $imgInfo = getimagesize($originalPath);
    
    if ($imgInfo) {
        // Create thumbnail dimensions (e.g., 150x150)
        $thumbWidth = 150;
        $thumbHeight = 150;

        $sourceImage = imagecreatefromstring(file_get_contents($originalPath));
        
        // Calculate aspect ratio to maintain proportions
        $ratio = min($thumbWidth / $imgInfo[0], $thumbHeight / $imgInfo[1]);
        $newWidth = $imgInfo[0] * $ratio;
        $newHeight = $imgInfo[1] * $ratio;

        $thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
        
        // Resize logic using imagecopyresampled for better quality
        imagecopyresampled(
            $thumbImage, 
            $sourceImage, 
            0, 0, 
            0, 0, 
            $thumbWidth, $thumbHeight, 
            $newWidth, $newHeight
        );

        // Save thumbnail back to the source variable or a temp file for saving
        imagejpeg($thumbImage, $originalPath, 85); // Overwriting original with resized? No.
        
        // Better approach: Save both separately or keep one in memory
        // For this example, we assume we process and save the thumb to a specific path
        imagejpeg($sourceImage, dirname($originalPath) . '/thumbs/' . $newFileName, 85);

        // Prepare data for database insertion using Prepared Statements
        $imageData = file_get_contents($originalPath);
        
        // Use PDO or MySQLi with prepared statements to prevent SQL Injection
        $stmt = $pdo->prepare("UPDATE users SET user_pic = :data WHERE id = :id");
        $thumbStmt = $pdo->prepare("INSERT INTO userphotos (photo_ownerid, photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES (:ownerid, 1, 'Profile Picture', 'Profile Picture', :data)");

        $stmt->execute([':data' => $imageData, ':id' => $_SESSION['id']]);
        $thumbStmt->execute([
            ':ownerid' => $_SESSION['id'], 
            ':data' => file_get_contents(dirname($originalPath) . '/thumbs/' . $newFileName)
        ]);

        // Optional: Clean up temporary files if not needed on disk long term
        // unlink($originalPath); 
    } else {
        die('Could not read image.');
    }
}

The key takeaway here is to treat binary data as bytes, not strings. When inserting into a longblob, you should pass the raw binary string directly to the prepared statement without any escaping functions like addslashes. The database handles the encoding appropriately for BLOB columns.

Furthermore, storing large images in the database is generally discouraged for high-traffic applications. While longblob fields work for small datasets or specific legacy systems, modern architecture prefers storing the file path in the database (e.g., /uploads/user_123.jpg) and keeping the actual file on the filesystem or an object storage service like AWS S3. This approach simplifies garbage collection, allows for easy resizing without re-uploading, and reduces memory pressure during queries.

If you require a managed solution where image processing is abstracted away from your application logic, exploring platforms that offer media management libraries can streamline this workflow. Resources like https://laravelcompany.com often provide insights into integrating such tools efficiently within a Laravel ecosystem, though the core principles of binary data handling remain consistent across languages and frameworks.

Our network