Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

photo album

Status
Not open for further replies.
Aug 23, 2004
174
US
I am trying to either find software or write my own to be able to upload pictures, create directories, and display the pictures on a page. I want to be able to have the main photo page on the site have links to each of the directories and be able to display those pictures. I tried using phpAlbum but I didn't really like it. Any help is appreciated.
 
Using a recursive function that uses opendir, to open a directory and list files, is a pretty simple approach.

I did once, and it wasn't very difficult to accomplish.

You can also use glob() to get the dir contents, and then echo out the file names. You would then have to construct the image tags to take the file names and be surrounded by a <a href> tag so they are also links.

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
On one of my sites, I've used Gallery 2 by Menalto (as jpadie has recommended).

I also use a flash-based image viewer called Monoslideshow which is quite slick, but not free (however it only costs a nominal amount).

Some others which I haven't used, but are offered by my web-host are:
- 4Images Gallery
- Coppermine Photo Gallery

Clive
Runner_1Revised.gif

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To err is human, but to really foul things up you need a computer." (Paul Ehrlich)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To get the best answers from this forum see: faq102-5096
 
I've looked at a few software options and most of them are too complicated for what I need. What I am thinking about doing is using an html form to get an album name and upload the images and then store that information in a mysql database. Then just select by the album name to display pictures from that album.

One problem is naming the uploaded files. I can get the files to upload to the server but if 2 files have the same name the old one is just replaced. Is there anyway to change the file name so that old pictures with the same name wont get over written?
 
then vacunita's implied idea of keeping albums = directories and recursively scanning the directories sounds like what you need.

naming the files is not quite so relevant, you can always use tempnam to generate a unique id. store a mapping in a text file along, perhaps with some comments.

then for display you can use one of the fab mechanisms at cssplay.co.uk.

i have a few hours plane journey coming up. if i get the muse hits i might try and code a lightweight gallery such as the one you describe. if i do, i'll post the code back into this thread.
 
Here is my php for uploading and creating the albums:

<?php

$album = $_POST['album'];

mkdir($album, 0777);

$target = "/home/stimul/public_html/RP/cms/uploads/".$album."";

foreach ($_FILES["pics"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pics"]["tmp_name"][$key];
$name = $_FILES["pics"]["name"][$key];
move_uploaded_file($tmp_name,"$target/$name");
}
}
?>

The directories(albums) get created and files uploaded alright. But when I try to delete the files or directories I get an access denied error.
 
here is my offering for crtique

it consists of two files
template.tpl (the html template file)
index.php (the scripts).

other files get created on first use. it's very lightweight and stores all its metadata in text files.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Light-Weight Photo Album <?=$albumName?></title>

<style type="text/css">
#scroller{width:600px;height:360px;position:relative;padding:5px 0;background:#fff}
#scroller em{display:block;width:229px;height:175px;position:absolute;top:0;right:0;border:1px solid #ddd}
#scroller span{display:block;width:360px;height:365px;position:absolute;top:0;left:0;border:1px solid #ddd}
#scroller span b#copyright{font-size:10px;color:#888;position:absolute;bottom:5px;right:20px;font-family:georgia,verdana,arial,sans-serif;font-weight:normal}
#scroller b#thumbs{display:block;width:220px;height:175px;overflow:auto;float:right;margin-top:175px;border:1px solid #ccc;border-width:1px 0 1px 1px;padding:5px}
#scroller b#thumbs a{display:block;float:left;margin:0 10px 10px 0;background:#f8f8ff;width:50px;height:50px;border:1px solid #000}
#scroller b#thumbs a img{width:50px;height:50px;border:0}
#scroller b#thumbs a:hover{border:1px dotted #ccc;background:#fff url(./images/click_on.gif)}
#scroller b#thumbs a:active,#scroller b#thumbs a:focus{border:1px solid #fff;background:#fff;outline:0}
#scroller b#thumbs a:hover img{display:block;position:absolute;background:#aaa;z-index:500}
#scroller b#thumbs a:active img,#scroller b#thumbs a:focus img{display:block;position:absolute;background:#aaa;z-index:100}
#scroller b#thumbs a:hover img.hr,#scroller b#thumbs a:focus img.hr{width:160px;height:120px;right:35px;top:7px;border:1px solid #333}
#scroller b#thumbs a:hover img.vt,#scroller b#thumbs a:focus img.vt{width:120px;height:160px;right:55px;top:7px;border:1px solid #333}
#scroller b#thumbs a:active img.hr,#scroller b#thumbs a:focus img.hr{width:320px;height:240px;left:20px;top:7px;border:1px solid #333}
#scroller b#thumbs a:active img.vt,#scroller b#thumbs a:focus img.vt{width:240px;height:320px;left:60px;top:7px;border:1px solid #333}
</style> 
<!--[if IE]>
<style type="text/css">
#scroller b{scrollbar-arrow-color:#333;scrollbar-3dlight-color:#bbb; scrollbar-highlight-color:#eee;scrollbar-face-color:#bbb;scrollbar-shadow-color:#eee;scrollbar-darkshadow-color:#bbb;scrollbar-track-color:#fff}
</style> 
<![endif]-->
</head>

<body>
<!--- template html goes here --->
<?=$contentObject?>
</body>
</html>

Code:
<?php
/*
This document does all the heavy lifting
*/
define ("ALBUMFILE", "./albums.txt", false); //the name of the database
define ("MAXSIZE", 400, false); //this is the max size in pixels that the images will be scaled to
define ("IMAGEPATH", "./images/", false); // the relative path (or absolute) to save albums
define ("ALLOWZIP", true); //defines whether bulk uploads are allowed in zip format.  Must support unix ZIP commands.
define ("METADATA", "./metadata.txt");
define ("INIT", true); // change this to false to stop the file initialisation
define ("MAXFILESIZE", "3MB"); //maximum file upload size;

switchboard(); 	//start the machine
function switchboard(){
	if (INIT) init();
	$action = isset($_POST['action']) ? $_POST['action'] : '';
	switch ($action) {
		case "submitNewAlbum":
			processNewAlbumRequest();
		break;
		
		case "uploadfile":
			processUploadedFile();
		break;
		
		case "New Album":
			newAlbumForm();
		break;
		
		case "Upload":
			displayUploadForm();
		break;
		
		case "Display":
			displayAlbum();
		break;
		default:
			displayAlbum();
	}
}
function init(){
	if (!file_exists(ALBUMFILE)){
		$fh = fopen(ALBUMFILE, "w");
	}
	if (!file_exists(IMAGEPATH)){
		mkdir(IMAGEPATH);
	}
	if (!file_exists(METADATA)){
		$fh = fopen(METADATA, "w");
	}
}
function newAlbumForm($msg=""){
	//make the album name sticky from page refreshes
	$albumName = isset($_POST['albumName']) ? $_POST['albumName'] : '';
	$msg = (empty($msg)) ? NULL: '<div class="errorMessage">'.$msg.'</div>';
	$contentObject = <<<HTML
$msg
<form method="post" action="{$_SERVER['PHP_SELF']}" >
<fieldset>
	<legend>New Album</legend>
	Album Name: <input type="text" maxlength="255" value="$albumName" name="albumName"  /><br/>
	<input type="submit" name="submit" value="Create Album" />
	<input type="hidden" name="action" value="submitNewAlbum"/>
</fieldset>
</form>
HTML;
	require 'template.tpl';
}

function processNewAlbumRequest(){
	//prep the album name
	if (!empty($_POST['albumName'])){
		$albumName = trim($_POST['albumName']);
	} else {
		newAlbumForm("No Album Name Provided");
		exit();
	}
	$albums = getAlbumNames();
	//check that the album name does not exist
	if (in_array($albumName, $albums)){
		newAlbumForm("Sorry, that album name has already been taken");
		exit();
	} else {
		$fh = fopen(ALBUMFILE, "ab");
		fwrite ($fh, $albumName."\r\n");
		fclose ($fh);
	}
	//create the album directory
	mkdir(IMAGEPATH."$albumName");
	displayAlbum();
	
}

function getAlbumNames(){
	//returns an array of album names or a blank string if there are no albums
	$albums = array();
	$fh = @fopen(ALBUMFILE, "rb");
	if (!$fh){
		return '';
	} else {
		while ( ($data = fgetcsv($fh, 1024, ",", '"')) !== false){
			$albums[] = $data[0];
		}
		fclose ($fh);
		return $albums;
	}
}
function displayUploadForm($msg=NULL){
	$maxsize = MAXFILESIZE;
	$msg = (empty($msg)) ? NULL: '<div class="errorMessage">'.$msg.'</div>';
	$shortdescription = (isset($_POST['shortdescripton'])) ? $_POST['shortdescripton'] : '';
	$albums = getAlbumNames();
	$select = "<select name=\"albumName\">\r\n";
	foreach ($albums as $album){
		$select .= "\t<option value=\"$album\">$album</option>\r\n";
	}
	$select.= "</select>";
	$contentObject = <<<HTML
$msg
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data" >
<fieldset>
	<legend>Upload images</legend>
	<p>You can upload gif, png or jpegs either singly or in bulk as a zip file</p>
	Choose file (max $maxsize): <input type="file" name="upload" /><br/>
	Short description: <input type="text" maxlength="255" name="shortdescription" value="$shortdescription" /><br/>
	Which album: $select
	<input type="submit" name="submit" value="Upload" />
	<input type="hidden" name="action" value="uploadfile" />
</fieldset>
</form>
HTML;
	require 'template.tpl';
}
function processUploadedFile(){
	//check for errors
	$msg = "";
	if (isset($_FILES['upload'])){
		switch ($_FILES['upload']['error']){
			case 0:
				break;
			case 1:
			case 2:
				$msg = "The uploaded file is too large"; 
				break;
			case 3:
				$msg = "The uploaded file was only partially uploaded";
				break;
			case 4:
				$msg = "No file was uploaded";
				break;
			case 6:
			case 7:
			case 8;
				$msg = "There was a problem saving ths uploaded file.";
				break;
		}
	}
	
	//if we have a problem, tell the user
	if (!empty($msg)){
		displayUploadForm($msg);
		exit();
	}
	
	//check the file type.
	//simple check against the file extension.  not ideal...
	if (!empty($_POST['upload']['type'])){
		$type = $_POST['upload']['type'];
	}else {
		$type = getFileType($_FILES['upload']['name']);
	}
	switch ($type){
		case "application/x-zip":
			if (ALLOWZIP){
				processUploadedZipFile($_FILES['upload']['tmp_name']);
			} else {
				displayUploadForm("Sorry we do not allow Zip files");
			}
			break;
		case "unsupported":
			displayUploadForm("Only zip files and jpegs are allowed to be uploaded");
			exit();
			break;
		default:
			processUploadedPhoto($_FILES['upload']['tmp_name'], $type);		
	}
	displayAlbum();
}

function processUploadedPhoto($file, $type){
	//grab a uniqueID
	if (!isset($_POST['albumName'])){
		displayUploadForm("You have not selected an album");
		exit();
	}
	$albumName = $_POST['albumName'];
	$albums= getAlbumNames();
	if (!in_array($albumName,$albums)){
		displayUploadForm("You have not selected an existing album");
	}
	$extension = getExtensionFromType($type);
	$uid = uniqid("photo_", true) .".$extension";
	$file = reSizePhoto($file, $type);
	if (rename($file, IMAGEPATH.$albumName.'/'.$uid) === false){
		displayUploadForm("Problem saving file");
		exit();
	}
	//save the metadata for the file
	$shortdescription = addslashes (trim($_POST['shortdescription']));
	$fh = fopen(METADATA, "ab");
	flock($fh, LOCK_EX);
	fwrite($fh, "\"$albumName\",\"$uid\",\"$shortdescription\", \"".$GLOBALS['orientation']."\"\r\n");
	fclose ($fh);
}


function processUploadedZipFile($file){
	//dummy out for the time being...
	//alpha code
	$dir = "./".uniqid("tempzip_", true) .'/';
	mkdir ($dir);
	$command = "unzip $file -d $dir";
	//unzip the file to the new directory
	exec (escapeshellcmd($command));
	$fh = opendir($dir);
	while ( false !== ($file = readdir($fh))){
		if (!is_file($file)){
			//do nothing
		}
		//really need a function to test the filetype naturally here ...
		$type = getfiletype($dir.$file);
		$extension = getExtensionFromType($type);
		if ($type  !== "unsupported"){
			processUploadedPhoto($dir.$file,$type);
		} else {
			//do nothing
		}
	}
	removeDirectory($dir, false);
	
}
function getfiletype($file){
	if (function_exists("mime_content_type")){
		return(mime_content_type($file));
	}else{
		$ext = getExtension($file);
		switch ($ext){
			case "jpeg":
			case "jpg":
				return "image/jpeg";
			break;
			case "gif":
				return "image/gif";
			break;
			case "png":
				return "image/png";
			break;
			case "zip":
				return "application/x-zip";
				break;
			default:
				return "unsupported";
		}
	}
}
function getExtensionFromType($type){
	switch ($type){
		case "image/jpeg":
			return "jpeg";
		break;
		case  "image/gif":
			return "gif";
		break;
		case  "image/png":
			return "png";
		break;
	}
}
function getExtension($file){
	//really need a better way of doing this...
	$tmp = explode(".", $file);
	$type = $tmp[count($tmp)-1];
	return strtolower($type);
}
function reSizePhoto($file, $type){
	$newsize = MAXSIZE;
	//we know it is a jpeg because this is a limited applet
	//but allow for future expansion! 
	set_time_limit(0);
	switch ($type) {
		
		case 'image/jpeg':
			$src_img = imagecreatefromjpeg($file);
			$func = 'imagejpeg';
			$ext = '.jpeg';
			break;
		case 'image/gif':
			$src_img = imagecreatefromgif($file);
			$func = 'imagegif';
			$ext = '.gif';
			break;
		case 'image/png':
			$src_img = imagecreatefrompng($file);
			$func = 'imagepng';
			$ext = '.png';
			break;
		case 'image/bmp':
			$src_img = imagecreatefromwbmp($file);
			$func = 'imagewbmp';
			$ext = '.bmp';
			break;
		default:
			displayUploadForm("error - file is not of a supported image type");
			exit();
	}
	
	if ($src_img == '') {
		displayUploadForm("error - file is not a $type file");
		exit();
	}
	
	//get current image sizes
	
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	
	if ($old_x > $old_y){
		$GLOBALS['orientation'] = "hr";
		$thumb_w=$newsize;
		$thumb_h=$old_y*($newsize/$old_x);
	} elseif ($old_x < $old_y) {
		$GLOBALS['orientation'] = "vt";
		$thumb_w=$old_x*($newsize/$old_y);
		$thumb_h=$newsize;
	} else {
		$GLOBALS['orientation'] = "hr";
		$thumb_w= $thumb_h = $newsize; 
	}
	
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
	
	$func($dst_img,$file); 
	imagedestroy($dst_img);
	imagedestroy($src_img);	
	return $file;
}

function displayAlbum(){
	$albums = getAlbumNames();
	if (count($albums) === 0) {newAlbumForm();exit();}
	$albumName = (isset($_POST['albumName']))?$_POST['albumName']:$albums[0];
	$select = "<select name=\"albumName\">\r\n";
	foreach ($albums as $album){
		$selected = ($album === $albumName) ? "selected=\"selected\"": '';
		$select .= "\t<option value=\"$album\" $selected >$album</option>\r\n";
	}
	$select.= "</select>";
	$contentObject = <<<HTML
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data" >
<fieldset>
	<legend>Choose Album</legend>
	$select	<input type="submit" name="action" value="Display" /><br/>
	or <input type="submit" name="action" value="New Album" /> <input type="submit" name="action" value="Upload" />
</fieldset>
</form>
HTML;
	$contentObject .= <<<HTML
<div id="scroller">
<em></em>
<span><b id="copyright">&copy 2007 Stu Nicholls</b></span> 
<b id="thumbs">
LINKS
</b>
</div>
HTML;
	//now get the file list
	$fh = @fopen(METADATA, "rb") or die("cannot open metadata file");
	$links = '';
	while (false !== ($data = fgetcsv($fh, 2048, ",", '"'))){
		if ($data[0] == $albumName){
			$src = IMAGEPATH.$data[0].'/'.$data[1];
			$links .= <<<HTML
<a href="#nogo"><img class="{$data[3]}" src="$src" alt="{$data[2]}" title="{$data[2]}" /></a>
HTML;
		}
	}
	$contentObject = str_replace("LINKS", $links, $contentObject);
	require 'template.tpl';
}

function removeDirectory($dirname,$only_empty=false) {
	//taken from php.net user notes on rmdir()
    if (!is_dir($dirname))
        return false;
    $dscan = array(realpath($dirname));
    $darr = array();
    while (!empty($dscan)) {
        $dcur = array_pop($dscan);
        $darr[] = $dcur;
        if ($d=opendir($dcur)) {
            while ($f=readdir($d)) {
                if ($f=='.' || $f=='..')
                    continue;
                $f=$dcur.'/'.$f;
                if (is_dir($f))
                    $dscan[] = $f;
                else
                    unlink($f);
            }
            closedir($d);
        }
    }
    $i_until = ($only_empty)? 1 : 0;
    for ($i=count($darr)-1; $i>=$i_until; $i--) {
        @rmdir($darr[$i]);
	}
    return (($only_empty)? (count(scandir)<=2) : (!is_dir($dirname)));
}
?>
 
Upload image file in php and save in mysql database

CREATE TABLE test_pic
(
name VARCHAR(30),
email VARCHAR(30),
phone VARCHAR(30),
photo VARCHAR(30)
);

--------------------------------------------------------------------------

add_pic.php, view_pic_data.php codes:


add_pic.php:

Code:
<?php 

//This is the directory where images will be saved 
$target = "images/"; 
$target = $target . basename( $_FILES['photo']['name']); 

//This gets all the other information from the form 
$name  =  $_POST ['name']; 
$email =  $_POST ['email']; 
$phone =  $_POST ['phone']; 
$pic   = ($_FILES['photo']['name']); 

// Connects to your Database 
mysql_connect("localhost", "dml", "iud") or die(mysql_error()); 
mysql_select_db("rml") or die(mysql_error()); 

//Writes the information to the database 
mysql_query ("INSERT INTO test_pic VALUES ('$name', '$email', '$phone', '$pic')"); 

//Writes the photo to the server 

if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
	echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; 
else 
	echo "Sorry, there was a problem uploading your file."; 

?> 

<form enctype="multipart/form-data" action="add_pic.php" method="POST"> 

	Name:   <input type="text" name = "name">  <br /> 
	E-mail: <input type="text" name = "email"> <br /> 
	Phone:  <input type="text" name = "phone"> <br />
	Photo:  <input type="file" name = "photo"> <br />

	<input type="submit" value="Add"> 
</form>
--------------------------------------------------------------------------

[/code]

view_pic_data.php:

Code:
<?php 

mysql_connect("localhost", "dml", "iud") or die(mysql_error()); 
mysql_select_db("rml") or die(mysql_error()); 

//Retrieves data from MySQL 
$data = mysql_query("SELECT * FROM test_pic") or die(mysql_error()); 

//Puts it into an array 
while($info = mysql_fetch_array( $data )) 
{ 
	echo "<img src=[URL unfurl="true"]http://localhost/images/".$info[/URL]['photo'] ." width=\"150\" height=\"113\"> <br>"; 
	echo "Name:  ".$info['name']   . "<br>"; 
	echo "Email: ".$info['email'] . " <br>"; 
	echo "Phone: ".$info['phone'] . " <hr>"; 
}

?>
 
I have posted my code onto a sandbox site at:

as per the above, it has the following functionality:

accepts png, gif, jpeg
upload singly
upload by zip file
resizes each image on upload (configurable size)
no database required
album creation (each photo goes into an album - which corresponds to a directory).

to do:
re-write the bulk upload to insert an intermediate step to provide comments on each photo.
add to the template to display the comments for each photo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top