Skip to Content
Course content

48: Building a File Upload and Gallery Script

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of a file upload script like a high-security mailroom. When a package arrives, the mail clerk doesn't just take the box and put it directly on the CEO's desk. First, they check the label to see what it is. Then they weigh it to make sure it's not a 500-pound anvil. They might even X-ray it to ensure there isn't anything dangerous inside. Only after it passes these checks does the clerk move the package from the temporary loading dock to a specific, organized shelf in the warehouse.

In PHP, the "loading dock" is your server's temporary directory. The "checks" are your validation logic, and the "warehouse shelf" is the final folder where you'll store the images for your gallery. If you skip the mailroom process and just trust the package, you're essentially letting strangers put whatever they want onto your server—which is a great way to get hacked.

Wrestling with the $_FILES Array

Unlike a standard text input, files aren't sent via $_POST. They live in their own superglobal: $_FILES. But before you even touch that array, you have to make sure your HTML form has the correct attribute: enctype="multipart/form-data". I can't tell you how many times I've spent an hour debugging a "missing file" issue only to realize I forgot that one line of HTML. Without it, PHP will never see the file.

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="gallery_image">
    <button type="submit">Upload</button>
</form>

When the form submits, $_FILES['gallery_image'] becomes an array containing the original name, the temporary path on the server, the error code, and the file size. We care most about tmp_name (where it is now) and name (what it was called on the user's computer).

Don't Let Users Break Your Server

Here is where we act like the skeptical mail clerk. You should never trust the name provided by the user. A malicious user could upload a file named shell.php, and if you move that into your web root, they can execute code on your server. I always recommend renaming the file to something random or using a timestamp.

We also need to check the MIME type. Don't just trust the file extension; use finfo_file or mime_content_type to verify it's actually an image. I usually limit uploads to a few megabytes because I've seen a single 100MB "profile picture" crash a small shared hosting account.

$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$fileType = mime_content_type($_FILES['gallery_image']['tmp_name']);

if (!in_array($fileType, $allowedTypes)) {
    die("Nice try, but we only accept images here.");
}

$uploadDir = 'uploads/';
$fileName = time() . '_' . basename($_FILES['gallery_image']['name']);
$targetPath = $uploadDir . $fileName;

if (move_uploaded_file($_FILES['gallery_image']['tmp_name'], $targetPath)) {
    echo "File successfully moved to the warehouse!";
}

Turning a Folder into a Visual Gallery

Now that we have files piling up in our uploads/ folder, we need a way to show them. Instead of manually tracking every file in a database (which you should do for a professional app), we can use glob() for a quick-and-dirty gallery. It's a powerful function that finds pathnames matching a specific pattern.

I like using a simple foreach loop to wrap these results in HTML image tags. To keep the page from looking like a chaotic mess, I usually wrap the output in a CSS grid. It's a clean way to transform a directory of files into a curated visual experience.

$images = glob("uploads/*.{jpg,jpeg,png,gif}", GLOB_BRACE);

echo '<div class="gallery-grid">';
foreach ($images as $image) {
    echo "<img src='$image' alt='Gallery Image' style='width:200px; margin:10px;'>";
}
echo '</div>';



📋 Practical Task

Build a "Community Travel Photo Archive"

Your task is to create a functional image upload and gallery system. Your project must include:

  • An HTML form that allows a user to select an image file.
  • A PHP processing script that:
    • Validates that the file is actually an image (JPEG, PNG, or GIF).
    • Rejects any file larger than 2MB.
    • Renames the file using uniqid() to prevent filename collisions.
    • Moves the file into a folder named archive/.
  • A display section below the form that automatically scans the archive/ folder and displays all uploaded images in a simple grid of thumbnails.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.