May 062012
 

This is just a VERY basic gallery that you can modify to suit your needs. For example you could add columns in the database and store more info about the images (date, size, tags etc.). You could very easily make the output use Lightbox or similar images viewers. And you could of course do a very solid file validation check.

Just to make it clear, I’m not doing any mime verification or size checking of the images, no login or session check (which would be used for uploading or deleting images) and no fancy presentation of the images. This is just a rudimentary , minimal gallery for you to get started. Think of it as a sponge cake base recipe.

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.
  • 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=MyISAM 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
// This is just my database connection.
include 'includes/db_connect.php';

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

/* Split the filename at every dot, take the last part and put it in $ext
(this will be the file extension) */
$splits = explode(".", $filename);
$n = count($splits)-1;
$ext  = '.'.$splits[$n];

/* To get away from any pesky non-standard character problems, weird or duplicate
filenames I swap the filename for an 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_basnumber = 10000000;
$new_filename = $new_filename_basnumber.$ext;

while (file_exists("images/$new_filename")) {
	$new_filename_basnumber++;
	$new_filename = $new_filename_basnumber.$ext;
}

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

// 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';

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

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

	/* If a post is missing the physical image file, delete it from the database
	this is to keep redundant data to a minimum */
	if (!file_exists("images/$filename")) {
		mysql_query("DELETE FROM gallery WHERE id='$id'");
	}
	else {
		echo '
		<p>
		<a href="images/'.$filename.'" title="'.$title.'" >
			<img src="images/'.$filename.'" title="'.$title.'" width="100"/>
		</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';
// 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'];

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

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

  One Response to “How to make a simple PHP gallery”

  1. [...] This is an augmented version of this [...]

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>