Solved

Create Photo Gallery using PHP and Dreamweaver

Posted on 2008-06-20
2
1,688 Views
Last Modified: 2013-12-12
Hello
I wish to Create DataDriven Photo Gallery using PHP Mysql and Dreamweaver Server Behaviors.

Below is an example of the end result I am looking for.
 I have a website with a thumbnail gallery. When I click one of the thumbnail images a large image is  displayed. There are 12 thumbnail images.
(example of gallery at http://www.studio10photography.co.uk/gallery.php)

I want to create a form so I can upload new images to the database which will replace the existing images on the gallery page.

Basically, I want a form with a browse for file button and submit button.) which will submit the image information to the database and display it on the page using repeating regions instead of 12 separate fields each storing 1 image

I can develop using dreamweaver server behaviours and can create insert | edit & delete forms to enter data into a database but this image upload problem has me stumped!

0
Comment
Question by:kevinb4940
2 Comments
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 21834862
Kevin, here is my upload-and-resize photo script.  It has some local functions, so some of it will look like "pidgin code" but you should be able to figure most of it out.  It does the browse and upload.  

Hope that helps, ~Ray
<?php // admin_photos.php
$config_page= getcwd() . '/_config.php'; require_once($config_page);
 
access_control();
if (!admin_access_control()) { die('Admin Error'); }
 
/* ********************************************************************************************* */
/* comment lines will work if GD2 is not installed, but will make poorer images                  */
/*                                                                                               */
// MAKE AN IMAGE INTO THE RIGHT SIZE FOR PAGE DISPLAY
function create_right_size_image($image, $width=720) {
 
	$source = imagecreatefromjpeg("$image");
 
	$imageX = imagesx($source);
	$imageY = imagesy($source);
 
	if ($imageX <= $width) {
return FALSE;
}
	if ($imageX > $width) {
		$tnailX = $width;
		$tnailY = (int) (($tnailX * $imageY) / $imageX );
	} else {
		$tnailX	= $imageX;
		$tnailY = (int) (($tnailX * $imageY) / $imageX );
	}
 
	$target = imagecreatetruecolor($tnailX, $tnailY);
//	$target = imagecreate($tnailX, $tnailY);
	imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
//	imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
 
return $target ;
}
/* ********************************************************************************************* */
 
/* ************************************************************************* */
//
// COPY A FISH-PHOTO.JPG FILE INTO THE /{$photos}/ DIRECTORY
// FILE NAME FORMAT FOR TOURNAMENTS: T_{$t_key}_{$sequence}.xxx
// FILE NAME FORMAT FOR SERIES:      C_{$c_key}_{$sequence}.xxx
// FILE NAME FORMAT FOR ANGLERS:     A_{$a_key}_{$sequence}.xxx
//
// THE FILE NAME IS A KEY TO THE CAPTION IN THE DATA BASE
//
function copy_file_to_data_base($path_to_file, $caption) {
	global $db_connection, $my_dbt_prefix;
	global $photos;
 
// UNCONDITIONALLY DELETE ANY PREVIOUS INFORMATION ABOUT THIS IMAGE
	$sql	= "SELECT _key, filename FROM {$my_dbt_prefix}_PHOTOS WHERE filename = \"$path_to_file\" ";
	if (!$r	= mysql_query("$sql", $db_connection)) { non_fatal_query_error($sql); }
	while ($row	= mysql_fetch_assoc($r)) {
		$_key		= $row[_key];
		$dsql	= "DELETE FROM {$my_dbt_prefix}_PHOTOS WHERE _key = $_key LIMIT 1";
		if (!$d	= mysql_query("$dsql", $db_connection)) { non_fatal_query_error($dsql); }
	}
 
// WRITE THE INFORMATION INTO THE DATA BASE
	$isql	= "INSERT INTO {$my_dbt_prefix}_PHOTOS () VALUES ()";
	if (!$i	= mysql_query("$isql", $db_connection)) { non_fatal_query_error($isql); die(); }
	$_key	= mysql_insert_id($db_connection);
 
	$usql	= "UPDATE {$my_dbt_prefix}_PHOTOS SET ";
	$usql	.= "filename	= \"$path_to_file\", ";
	$usql	.= "caption		= \"$caption\" ";
	$usql	.= "WHERE _key = $_key LIMIT 1";
 
	$errmsg	= TRUE;
	if (!$u	= mysql_query("$usql", $db_connection)) { $errmsg = non_fatal_query_error($usql); }
return ($errmsg);
}
/* ************************************************************************* */
 
// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos	= 'photos';
 
// UPLOAD PHOTOS COULD BE ANY OF THESE
$a_key		= get_clean_numeric_string($_GET[a]);
$c_key		= get_clean_numeric_string($_GET[c]);
$t_key		= get_clean_numeric_string($_GET[t]);
 
// TEST FOR ONLY ONE KIND OF KEY
$image_type	= '';
$act_key	= $a_key . $c_key . $t_key;
if		($act_key == '') { die('Admin Error Key'); }
if		($act_key == $a_key) { $image_type = 'A'; $image_key = $a_key; $get_key = "a=$a_key"; }
elseif	($act_key == $c_key) { $image_type = 'C'; $image_key = $c_key; $get_key = "c=$c_key"; }
elseif	($act_key == $t_key) { $image_type = 'T'; $image_key = $t_key; $get_key = "t=$t_key"; }
if		($image_type == '') { die('Admin Error Type'); }
 
$page_title	= "Admin | Upload Photo";
 
 
$errors	= array(
	0=>"<font color=green>Success!</font>",
	1=>"<font color=gold>The uploaded file exceeds the upload_max_filesize directive in php.ini</font>",
	2=>"<font color=gold>The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form</font>",
	3=>"<font color=gold>The uploaded file was only partially uploaded</font>",
	4=>"<font color=gold>No file was uploaded</font>",
	6=>"<font color=gold>Missing a temporary folder</font>",
	7=>"<font color=gold>Cannot write file to disk</font>"
);
 
 
if ( (empty($_GET['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
	top_of_page();
	?>
	<h2>Upload Photos for <?=$image_type?> <?=$image_key?></h2>
 
	<!-- nb:enctype -->
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>&p=1" method="POST">
	<input type="hidden" name="_form_token" value="<?=make_form_token()?>" />
	<!-- MAX_FILE_SIZE must precede the file input field -->
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<!-- Name of input element determines name in $_FILES array -->
	<p>
	Find the photo you want to upload, add a caption, then click the "Upload" button below.
	You control the order of the photos on the web pages by setting the "Sequence" number.
	If you upload four tournament photos you might want to give them numbers like 10, 20, 30, 40.
	With the photos numbered that way, if you wanted to add another between 10 and 20, you could just number it 15.
	</p>
 
	<table cellpadding="1" cellspacing="1" border="0">
	<tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
	<tr><td align="right"><span class="required">Caption: </span></td><td><input type="text" size="80" name="caption" autocomplete="off" /></td></tr>
	<tr><td align="right"><span class="required">Sequence: </span></td><td>	<input type="text" size="4" name="sequence" autocomplete="off" /> Number between 1 and 999</td></tr>
	<tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
	&nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
	</table>
	</form>
	<p>&nbsp;</p><!-- shim -->
 
 
 
	<h2>Photos for <?=$image_type?> <?=$image_key?></h2>
 
 
<?php // GET THE PHOTOS THAT ARE ALREADY UPLOADED
	$filen	= $image_type .'_'. $image_key .'_';
	$psql	= "SELECT * FROM {$my_dbt_prefix}_PHOTOS WHERE filename LIKE \"%$filen%\" ORDER BY filename ASC";
	// echo "<p>$psql</p>\n";
	if (!$p	= mysql_query("$psql", $db_connection)) { non_fatal_query_error($psql); die(); }
	while ($prow	= mysql_fetch_assoc($p)) {
		$fname	= $prow[filename];
		$captn	= stripslashes($prow[caption]);
		$fseqa	= explode('_', $fname);
		$fseqn	= $fseqa[2];
		$fseqa	= explode('.', $fseqn);
		$fseqn	= $fseqa[0];
		echo "<table cellpadding=\"1\" cellspacing=\"1\" width=\"99%\">\n";
		echo "<tr valign=\"top\">\n";
		echo "<td><strong>Seq #</strong><br /><i>$fseqn</i> &nbsp; </td>\n";
		echo "<td><strong>Caption</strong><br />$captn</td>\n";
		echo "<td nowrap align=\"right\"><span id=\"admin\" class=\"admin\"><a class=\"admin\" title=\"Delete Photo $fseqn ?\" class=\"admin\" href=\"admin_drop_photo.php?p=$fname\">X</a></span></td>\n";
		echo "</tr>\n";
		echo "</table>\n";
		echo "<p align=\"center\" width=\"99%\">\n";
		echo "<img alt=\"$fname\" src=\"$fname\" />\n";
		echo "<br clear=\"all\" /><hr width=\"90%\" />&nbsp;\n";
		echo "</p>\n";
	}
 
	end_of_page('N');
 
 
} else {
 
	if (!check_form_token()) { die('Admin Error: Token'); }
	top_of_page();
	echo "<h2>Results: Upload Photos for $image_type $image_key</h2>\n";
	echo "<p>\n";
// GET THE CAPTION
	$caption	= mysql_real_escape_string(get_clean_text_string($_POST[caption]), $db_connection);
 
// GET THE SEQUENCE NUMBER
	$seq	= intval(get_clean_numeric_string($_POST[sequence]));
	if ($seq > 999) { $seq = 999; }
	$seq	= str_pad("$seq", 4, '0', STR_PAD_LEFT);
 
// SYNTHESIZE THE NEW FILE NAME
	$f_type	= trim(strtolower(end(explode( '.', basename($_FILES['userfile']['name'] )))));
	$my_new_file	= getcwd() . '/' . $photos . '/' . $image_type .'_'. $image_key .'_'. $seq .'.'. $f_type;
	$my_file		= $photos . '/' . $image_type .'_'. $image_key .'_'. $seq .'.'. $f_type;
 
// MOVE THE FILE INTO THE DIRECTORY
	$overwrite	= $_POST['overwrite'];
	$error_code = $_FILES["userfile"]["error"];
	$file_size	= number_format($_FILES["userfile"]["size"]);
 
	if ($error_code != 0) {
		$error_message = $errors[$error_code];
		echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
		end_of_page('N');
	}
 
 
	if (!file_exists($my_new_file)) {
		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new_file)) {
			$upload_success = 1;
		} else {
			$upload_success = -1;
		}
	} else { // the file already exists
		echo "<b><i>$my_file</i></b> already exists.\n";
		if (empty($overwrite)) {
			$upload_success = 0;
		} else { // attempt to make a backup
			$now	= date('Y-m-d');
			$my_bak = $my_new_file . '.' . $now . '.bak';
			if (!copy($my_new_file, $my_bak)) {
				echo "<b>Attempted Backup Failed!</b>\n";
			}
			if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new_file)) {
				$upload_success = 2;
			} else {
				$upload_success = -1;
			}
		}
	}
 
	if ($upload_success == 2) { echo "It has been overwritten.\n"; }
	if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
	if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }
 
	if ($upload_success > 0) {
		echo "$file_size bytes uploaded.\n";
		chmod ($my_new_file, 0755);
		copy_file_to_data_base($my_file, $caption);
	}
 
	echo "</p>\n";
 
// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
	if ($upload_success > 0) {
		if ($imageblob	= create_right_size_image($my_new_file)) {
			imagejpeg($imageblob, $my_new_file);
		}
	}
 
	echo "<p><a href=\"$_SERVER[PHP_SELF]?{$get_key}\">Upload Another?</a></p>\n";
 
	if ($image_type == 'A') {
		echo "<p><a href=\"anglers.php?{$get_key}\">Check Angler Page</a></p>\n";
	}
 
	if ($image_type == 'C') {
		echo "<p><a href=\"series.php?{$get_key}\">Check Series Page</a></p>\n";
	}
 
	if ($image_type == 'T') {
		echo "<p><a href=\"results.php?{$get_key}\">Check Results Page</a></p>\n";
	}
 
	end_of_page('N');
}
?>

Open in new window

0
 

Author Closing Comment

by:kevinb4940
ID: 31469266
Thanks a lot for your help
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article provides the solution to a question (http://www.experts-exchange.com/Software/Photos_Graphics/Images_and_Photos/Q_28674207.html) posed here at Experts Exchange. The asker of the question has many JPG images in many folders, and all of t…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The goal of the tutorial is to teach the user the full work flow of how to use flash media encoder to stream onto YouTube.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

823 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question