(PHP) Simple gallery with thumbnail generation

By | May 8, 2013

This is an enhanced version of this

It’s a VERY simple php gallery. You could develop it in any direction. This one only supports jpg, but that could be augmented as well.
Here’s what it does:

  • Allows the user to choose an image and enter a title (or caption).
  • Uploads the image to a folder on the server.
  • Creates a thumbnail
  • Enters the filename and caption in a MySQL database.
  • Output all the images.

I have chosen to break this up in four files, to keep it separated nice and clean. This solution will need a MySQL database. (if you need info on that, follow some tutorial like this).

Also, you need to create a folder, with appropriate read/write-rules, named “images” in the same folder as these scripts.

First off… The MySQL database table should look something like this:

CREATE TABLE IF NOT EXISTS 'gallery' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'filename' varchar(128) NOT NULL,
  'title' varchar(1024) NOT NULL,
  PRIMARY KEY ('id')
) ENGINE= InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

And here’s the form (the ul-list is just to display the form in a somewhat non-horrible fashion):
gallery_form.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
	li {
		list-style: none;
	}
</style>

</head>

<body>

<form action="gallery_process.php" method="post" enctype="multipart/form-data">
<ul>
	<li>
    	Choose image
    </li>
	<li>
		<input type="file" name="file" id="file" />
	</li>
	<li>
    	Add title
    </li>
	<li>
		<input type="text" name="title" id="title" />
	</li>
	<li>
		<input type="submit" name="submit" />
	</li>
</ul>
</form>

</body>
</html>

Here’s the process that will save the image and update the database.
gallery_process.php

<?php
// FUNCTION:		image_to_thumb
// Parameters:
// $src: 			source jpeg
// $dest: 			destination file
// $thumb_width: 	width of thumbnail
// $thumb_quality: 	quality of thumbnail (0-100)
function image_to_thumb($src, $dest, $thumb_width, $thumb_quality) {

	// Read the source image
	$src_image = imagecreatefromjpeg($src);
	$src_width = imagesx($src_image);
	$src_height = imagesy($src_image);

	// Generate thumbnail height, relative to its width
	$thumb_height = floor($src_height * ($thumb_width / $src_width));

	// Create a new image with target dimensions
	$dest_image = imagecreatetruecolor($thumb_width, $thumb_height);

	// Copy source image to destination image, with new dimensions
	imagecopyresampled($dest_image, $src_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height);

	// create the physical thumbnail image to its destination
	imagejpeg($dest_image, $dest, $thumb_quality);

	// Free up resources
	imagedestroy($src_image);
	imagedestroy($dest_image);
}

// This is just my database connection
include 'includes/db_connect.php';

// path to images folder
$images_path = "images";
$images_path .= "/";

// Desired width of thumbnail, in pixels
$thumb_width = 150;

// Gather the information sent by the form
$temp_filename = $_FILES["file"]["tmp_name"];
$filename = $_FILES["file"]["name"];
$title = $_POST['title'];

// Check that the image is a jpeg.
$image_info_array = getimagesize($temp_filename);
if ($image_info_array['mime'] !== 'image/jpeg')
{
	echo "This script only supports jpeg images";
	// ... add appropriate  actions
}
else
{
	// Find file extension
	$ext = '.'.pathinfo($filename, PATHINFO_EXTENSION);

	// To get away from any filename problems the filename is swapped for a 8-digit number.
	// The loop will check if an image of that name exists and add 1 to the number until the filename is unique.

	$new_filename_basenumber = 10000000;

	while (glob($images_path.$new_filename_basenumber.'*'))
	{
		$new_filename_basenumber++;
	}

	$new_filename = $new_filename_basenumber.$ext;
	$thumb_name = $new_filename_basenumber."_thumb".$ext;

	// Move the file to the server and give it the generated name.
	move_uploaded_file($temp_filename, $images_path.$new_filename);

	// Make a thumbnail
	image_to_thumb($images_path.$new_filename, $images_path.$thumb_name, $thumb_width, 80);

	// Enter all information to the database and head over to the output
	mysql_query("INSERT INTO gallery (filename, title) VALUES ('$new_filename', '$title')");
	header("Location: gallery_output.php");
}
?>

Here’s the output:
gallery_output.php

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
</head>
<body>

<?php
// Database connection
include 'includes/db_connect.php';

// Set image folder path
$images_path = "images";
$images_path .= "/";

// Get all data from the database table
$result = mysql_query("SELECT * FROM gallery");

echo "<strong>Click the thumbnails to see full size image</strong><br />";

// Go through the table and output all images.
while ($row = mysql_fetch_array($result)) {
	$filename = $row['filename'];
	$title = $row['title'];
	$id = $row['id'];

	$thumb_filename = pathinfo($images_path.$filename, PATHINFO_FILENAME).'_thumb.'.pathinfo($images_path.$filename, PATHINFO_EXTENSION);

	echo '<p>
			<a href="'.$images_path.$filename.'" title="'.$title.'" ><img src="'.$images_path.$thumb_filename.'" title="'.$title.'" /></a>
			<a href="gallery_delete.php?id='.$id.'" onclick="return confirm(\'Are you sure you wish to delete the image?\')">Delete Image</a>
		</p>';

}
?>

<p><a href="gallery_form.php?">Add new image</a></p>

</body>
</html>

And last the delete image process:
gallery_delete.php 

<?php
// Connect to database
include 'includes/db_connect.php';

// Set image folder path
$images_path = "images";
$images_path .= "/";

// Get the database id of the post to delete
$id = $_GET['id'];

// First get the data and find the filename
$result = mysql_query("SELECT * FROM gallery WHERE id='$id'");
$row = mysql_fetch_array($result);

$filename = $row['filename'];

$thumb_filename = pathinfo($images_path.$filename, PATHINFO_FILENAME).'_thumb.'.pathinfo($images_path.$filename, PATHINFO_EXTENSION);
echo $thumb_filename;

// Then delete the file and the database post.
if (file_exists($images_path.$filename)) {
    unlink($images_path.$filename);
	unlink($images_path.$thumb_filename);
}
mysql_query("DELETE FROM gallery WHERE id='$id'");

// And head back to the output page
header("Location: gallery_output.php");
?>

Leave a Reply

Your email address will not be published. Required fields are marked *