Code lab · PHP + MySQL

PHP Image Upload & View

Upload images safely and display gallery from database.

Learning guide

Practising PHP and MySQL? Upload images safely and display gallery from database. We focus on PHP Image Upload & View here.

Configuration belongs in config.php (PHP) or a single app.js entry (browser labs)—not sprinkled through every page.

Read a section, predict what should happen, then run it. Logs and the browser network tab are part of the lesson.

If local setup is new to you, block an hour once for Apache/MySQL or Live Server, then reuse that stack for other guides.

Start from index.php when you open the reference tree. The optional package at the bottom matches this article.

Concepts you should understand

Authentication labs cover identity, sessions, and password hashing. Upload labs cover validation, storage layout, and metadata. AJAX labs cover HTTP verbs, JSON contracts, and separating view from API. Map each file in the reference section to one of these ideas.

Optional local lab setup

PHP labs assume a local MySQL schema imported from the teaching database.sql file. These steps describe a learning environment, not commercial software installation.

  1. Create a folder under your local web root named php-image-upload-view for this exercise.
  2. Start Apache and MySQL services on your machine (only needed for PHP/MySQL lessons).
  3. Import the bundled database.sql through phpMyAdmin to create practice tables.
  4. Adjust config.php credentials to match your local database user.
  5. Open http://localhost/php-image-upload-view/index.php and step through each screen while reading the source.
  6. Credentials for sandbox testing, if any, are documented only inside the private README.txt shipped with the practice archive—not on this public page.

Guided walkthrough

Begin by using the feature as a learner: submit empty forms, invalid emails, and edge cases. Watch how the UI responds, then locate the PHP or JavaScript responsible for that message. Trace variables from $_POST or fetch bodies down to SQL or DOM updates.

Rewrite one branch in your own words—rename fields, add comments, or log values with error_log or console.debug. If behavior changes unexpectedly, you have found a learning moment about sessions, scope, or async timing.

For topics like PHP Image Upload & View, compare your work against the annotated snippets below before peeking at the full reference tree. Spaced repetition (revisit the lesson days later) cements syntax into long-term memory better than a single rushed pass.

Annotated code samples

Each block is meant to be edited, not pasted blindly. Read the note under it, then try one small change.

Validating type and size on the server

<?php
$allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array(mime_content_type($tmp), $allowed, true) || $size > 2_000_000) {
    exit('Invalid file');
}

File extensions can be faked; mime_content_type inspects the temporary upload. A size cap limits disk abuse and denial-of-service attempts. Reject early before moving bytes into a public uploads folder.

If the sample uses a helper you do not recognise, look it up on PHP.net or MDN before copying it wholesale.

Using unpredictable stored file names

<?php
$stored = bin2hex(random_bytes(8)) . '_' . basename($originalName);
move_uploaded_file($tmp, __DIR__ . '/uploads/' . $stored);

Random bytes make filenames hard to guess, which reduces hot-linking and directory guessing attacks. move_uploaded_file only works on files PHP received via HTTP upload, which blocks arbitrary path tricks. Keep original names in the database for display, not as the on-disk path.

Upload handlers are a frequent target because they touch the filesystem. Validate type and size on the server, store files outside the web root when possible, and never execute uploaded content. These steps mirror what security auditors expect in real products, not just classroom demos.

Run the happy path first, then try empty fields or bad IDs on purpose.

Recording uploads in MySQL

<?php
$stmt = db()->prepare('INSERT INTO uploads (original_name, stored_name) VALUES (?, ?)');
$stmt->bind_param('ss', $originalName, $stored);
$stmt->execute();

The gallery reads from the database rather than scanning the folder, so you control order and metadata. Prepared inserts avoid SQL injection when filenames contain special characters. Deleting a row later should also remove the physical file to stay consistent.

Upload handlers are a frequent target because they touch the filesystem. Validate type and size on the server, store files outside the web root when possible, and never execute uploaded content. These steps mirror what security auditors expect in real products, not just classroom demos.

Security notes for students

Practice code deliberately simplifies reality. Before any production deployment, add HTTPS, rate limiting, logging, and professional review. Never reuse tutorial passwords in public systems. Remove sample accounts and disable verbose errors on live hosts.

Legal: Globaltuts.com is not responsible for security vulnerabilities if practice code is deployed on a live production server without proper sanitization. Read our practice project policy, Privacy Policy, and Disclaimer.

Reference materials for this lesson

Optional practice files to follow along after reading the guide above. Not required to understand the concepts.

  • README.txt
  • assets/style.css
  • config.php
  • database.sql
  • index.php
  • upload.php
  • uploads/.gitkeep

Archive folder name: php-image-upload-view/

Get practice archive (.zip)