Google Login with Google

How to Upload Images in PHP (Step-by-Step)

📌 How to Upload Images in PHP (Step-by-Step)

If you created a gallery page,
the next step is allowing users to upload images.

In this guide, you will learn:

file upload form
PHP upload handling
database storage
basic security
1️⃣ Create upload form

Add this HTML form:

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image" required>
<input type="text" name="title" placeholder="Title">
<textarea name="caption" placeholder="Caption"></textarea>
<button type="submit">Upload</button>
</form>

👉 enctype="multipart/form-data" is required for file upload.

2️⃣ Create upload.php

Create a new file:

/hosting/foliocraft/html/upload.php
3️⃣ Handle file upload (PHP)
<?php

require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

$title = $_POST['title'];
$caption = $_POST['caption'];

$file = $_FILES['image'];

$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];

// File extension
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Allowed extensions
$allowed = ['jpg', 'jpeg', 'png', 'gif'];

if (!in_array($ext, $allowed)) {
die("Invalid file type.");
}

// File size limit (2MB)
if ($fileSize > 2 * 1024 * 1024) {
die("File too large.");
}

// Create unique file name
$newName = uniqid() . '.' . $ext;

$uploadPath = 'uploads/' . $newName;

// Move file
if (move_uploaded_file($tmpName, $uploadPath)) {

// Insert into database
$stmt = $conn->prepare("INSERT INTO gallery (title, image_url, caption) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $title, $uploadPath, $caption);
$stmt->execute();

echo "Upload successful!";

} else {
echo "Upload failed.";
}
}
?>
4️⃣ Create uploads folder

Create a folder:

/hosting/foliocraft/html/uploads/

👉 Important:

Make sure it has write permission
Example:
chmod 755 uploads
5️⃣ Save to database

We already created gallery table earlier:

image_url → stores uploaded file path

Example stored value:

uploads/abc123.jpg
6️⃣ Display uploaded images

Inside gallery.php:

<img src="<?= $row['image_url'] ?>" width="300">
🔐 Security (Important)

Never skip this part.

✔ 1. File extension check
['jpg','png','gif']
✔ 2. File size limit
2MB limit
✔ 3. Unique file name
uniqid()
✔ 4. Prevent overwrite
Always generate new file name
✔ 5. (Advanced) MIME type check
mime_content_type($tmpName);
🔥 Final Result
Users can upload images
Images stored in /uploads
Path saved in database
Gallery page shows images
✅ Summary

To implement image upload:

Create form
Handle file in PHP
Save file
Store path in DB
Add security checks
💡 Next Step

You can extend this by:

delete image feature
edit image
drag & drop upload
multiple file upload
← Back to list
💬 Comments (0)