Building the back-end of a photo site
videos

Building the Back-End of a Photo Site

For those of you who have been following the last few screencasts, you must have noticed that each tutorial has been centered around a “photo site” theme. (See Scanning Folders With PHP, How to Dynamically Create Thumbnails, and Create a Photo-Admin Site Using PHP and jQuery. Today, we’ll build the backend for a photo site. This tutorial will teach you how to add, delete, and update photos.

Our Mission

  • Create a database that will store our images.
  • Create a home page that retrieves all of the photos that are stored in our database.
  • Allow the user to upload photos.
  • Write some validation to ensure that the user enters a proper description and chooses an image
  • Use jQuery to allow the user to asynchronously update and delete specific photos.

There is simply too much to cover as a written tutorial. I’ve included a few key points. Refer to the screencast for the complete tutorial.

The Database Structure

The database structure

Get the Photos From the Database

Get Photos Function
function getPhotos() {
	require 'database.php';
	$q = "SELECT id, tn_src FROM photo ORDER BY id desc";
	
	$result = $mysqli->query($q) or die($mysqli_error($mysqli));
	
	if($result) {
		while($row = $result->fetch_object()) {
			$tn_src = $row->tn_src;
			$src = $row->src;
			$id = $row->id;
		
			print '
  • <a href="review_image.php?id=' . $id . '"> <img src="' . $tn_src . '" alt="images" id="' . $id . '" /> </a> </li>'; print "\n"; } } }
  • Upload Photos

    Get Photos Function

    Form Validation

        if(strlen($_POST['description']) < 4) 
        $error['description'] = '

    Please enter a description for your photo.

    '; if($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename)) $error['no_file'] = '

    Please select an image, dummy!

    ';

    Update the Photo’s Description Asynchronously

    Get Photos Function
    $('#description').click(function() {
                var originalelement = this;
                var currentText = $(this).text();
    
    			$(this).fadeOut(100).before('');
    		
    		    $('#input').livequery('change', function() {
    	            var id = <?php echo $_GET['id'] ?>;
    			    var thisparam = this;
                    var newText = $(this).val();
                    
                    if (newText == '') {
                       newText = 'Please enter a description'; 
                    }
                              
    	            $.ajax({
    	                type: 'post',
    	                url: 'updatePhoto.php',
    	                data: 'id=' + id + '&description=' + newText,
    	    
    	                success: function() {
                            $(thisparam).remove();
    	                    $(originalelement).text(newText).fadeIn(1000);
    	                }
    	           });
                    
    		    });
    		});
    	});
    

    UpdatePhoto.PHP

    require 'database.php';
    
    $id = $_POST['id'];
    $d = addslashes($_POST['description']);
    
    if ($d == '') $d = 'Click here to enter a description.';
    
    $q = "UPDATE photo SET description='$d' WHERE id = $id"; 
    $result = $mysqli->query($q) or die('There was a problem updating this information.');
    
    if($result) echo "Your photo has been successfully updated.";
    

    Delete a Photo

    Get Photos Function
    	$(function() {
    		$('img').click(function() {
    		   	var id = $(this).attr('id');
    		   	var thisparam = $(this);
    			   	
    			$.ajax({
    				type: 'post',
    				url: 'delete.php',
    				data: 'id=' + id,
    				
    				success: function() {
    		
    					$(thisparam).parent('li').fadeOut('slow');
                        $('#result').remove();
    					var response = '

    Success. The image has now been removed!

    '; response += 'Return to Home Page
    '; $('body').append(response); } }); }); })

    Delete.PHP

    require 'database.php';
    
    $id = $_POST['id'];
    
    $q = "DELETE from photo WHERE id = $id";
    $result = $mysqli->query($q) or die("There was a problem!");
    
    if($result) header("location: index.php");
    

    Completion

    So that does it. You could implement a bit more security into this application. But the idea is that these pages would already be secured by using something similar to an ht-access file. From here on, the sky is the limit. You should consider adding tags to your images, creating albums, etc. This should get you started.

    Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
    • Benn Garnish

      Hey guys

      I worked out that for this to work you need php5 switched on your hosting server. How embarrassing.

      I was also struggling with images being added to the site but not displaying a thumbnail. But this was sorted as there wasn’t a final ‘else’ statement in the function for making the thumbnail image. Also the preg_match statements are case sensitive, so files with .JPG were not being added.
      So for this to be fixed i added this to the preg_match statements:

      if(preg_match(‘/[.]jpg$/’, strtolower($filename))) {
      $im = imagecreatefromjpeg($path_to_image_directory . $filename);
      } else if (preg_match(‘/[.]gif$/’, strtolower($filename))) {
      $im = imagecreatefromgif($path_to_image_directory . $filename);
      } else if (preg_match(‘/[.]png$/’, strtolower($filename))) {
      $im = imagecreatefrompng($path_to_image_directory . $filename);
      } else {
      print(“Error: The file ‘$filename’ is not a supported file type”);
      }
      }

      Hope this helps some of you.

      • http://i-tech-life.blogspot.com idrish

        Thanks a lot…This saved my day…a very handy tip worth noting…

      • http://twitter.com/Yanowski Miron Yanovsky

        easier way:

        if(preg_match(‘/[.]jpg$/i’, strtolower($filename))) {
        $im = imagecreatefromjpeg($path_to_image_directory . $filename);
        }

        i – that the register did not matter

    • Greg

      What if the users need to email their photos as attachments instead of uploading via a form?

    • whiskeyfrances

      This is great… With some extra coding and an ffmpeg-enabled hosting one could also take this to create a video site…

    • pauli

      hi, im looking for some kind of plugin that let users upload their images on my website(wordpress) and as the admin it lets me choose which one to display
      also when uploading the images the users can put some text.

    • Pingback: November Roundup « Craig Farrall’s Blog

    • http://www.themaxexp.com Max

      I have been working with this tutorial a lot, and I have learned a lot form it!

      For the people with the MySQLi problem, replace each string that uses it with:
      $result = mysql_query($q) or die(mysql_error());
      Make sure you select your database in database.php.

      The only problem I am still having is how to prevent SQL injection on delete.php. Any help would be great.

    • cdm

      hi
      First photo is uploaded but when try to upload second it displays error
      “Duplicate entry ’0′ for key 1″
      where is problem? can anyone help?

    • tn

      Love the tutorial – learnt heaps. Would love to know how to implement the album with the jQuery.
      “You should NEVER print/echo information within a function, only do returns. You should also never put the php and html in the same files, it should be separated using a template system”
      Could you please put me in the right direction for this – not knowing how to do this?
      Thanks.

    • tn

      RE: Max
      I changed all to mysql but in database.php:
      $mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name) or die(mysqli_error());
      when I change it to MySQL it says there is no class for it and if I change anything else it won’t connect to the database at all and says on line 9 in functions is error.
      Fatal error: Function name must be a string

      I got it too. Did some research and found out that there was a ‘$’ in front of mysqli_error on line 9 in functions.php where there shouldn’t be. That fixed it for me. Hope this helps.
      I did this but it still didn’t work. Any other suggestions?
      Thanks.

    • http://www.limess.nl/webdesign-groningen/ webdesign groningen

      Hi,

      Great tutorial. I was struggling with uploading images with php for a while. I’m a designer not a hardcore programmer, So this tutorial helped me out a lot.

      Greetings from groningen

    • Willabee Wombat

      When uploading, no error is displayed, an image link is displayed but no image. Looking in the image folder, no images have been created. I assume this is a permissions problem on an Windows NTFS partition. If I am in .NET I have to give the ASPNET account modify permission for this type of process.
      What account do I need to give permission in a PHP/Apache environment to make this application work?

    • Willabee Wombat

      OK tried again, brand Windows XP virtual machine in VMWare

      Installed latest WAMP

      Created myphotos DB and executed:

      CREATE TABLE IF NOT EXISTS `photo` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `description` text NOT NULL,
      `src` varchar(150) NOT NULL,
      `tn_src` varchar(150) NOT NULL,
      `album_id` tinyint(3) NOT NULL,
      PRIMARY KEY (`id`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

      Copied your solution and browsed index.php

      Only modifications made was to remove the $ throughout all code as recommended by commenter’s to give:

      $result = $mysqli->query($q) or die(mysqli_error($mysqli));

      Uploaded image (jpg) and had the following errors:

      Notice: Undefined property: stdClass::$src in C:\wamp\www\newPhotoSite\functions.php on line 15

      Notice: Undefined variable: error in C:\wamp\www\newPhotoSite\index.php on line 67

      Notice: Undefined variable: error in C:\wamp\www\newPhotoSite\index.php on line 68

      Entries are being submitted to database ok.

      Nothing gets written to images or images/tn folders

      functions.php Line 15 is:
      $src = $row->src;

      index.php Line 67 and 68 is:
      if ($error['no_file']) echo $error['no_file'];
      if ($error['description']) echo $error['description'];

      Any help appreciated.

    • polymaze

      Hello, I love the tutorial, however, I keep receiving an error message after I upload or delete an image (if deleting from individual photos).

      //after uploading an image
      Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\TESTS\newPhotoSite_backend\database.php:1) in C:\xampp\htdocs\TESTS\newPhotoSite_backend\functions.php on line 99

      //after deleting an image
      Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\newPhotoSite_backend\database.php:1) in C:\xampp\htdocs\newPhotoSite_backend\delete.php on line 11

      The lines the error messages are listing target the ( header(“location: index.php”); ) line.

      I’m not sure why I’m getting the error messages instead of the page redirecting back to the index, or how to fix the problem.

      Thanks

      • http://www.laceytechsolutions.co.uk Ben Lacey

        The headers error is quite common and I sometimes overlook this as well. Sending headers should be the first thing you do, before any other output is sent. EG:

        Hope this helps. If you need an

    • http://www.davidbeermann.com/ David

      Just another great tutorial. Thanks Jeff.

      Just one problem little problem. When you delete an image its references are wiped out from the database but the image and the thumbnail are still there. Is there a way to delete these files too? As I’m quite new to PHP it’ll probably take a while since I figure it out myself. So if someone could give me hint where to look for a solution I’d be very thankful.

      • Arkad

        havnt tried this but maybe just use the same code for deleting the original by making a duplicate and change the locations … maybe

      • http://shawntysco.com Shawn

        Try using “unlink”

      • Dan

        Good call Shawn.
        If you followed the tutorial pretty closely, then I found the easiest way to make this change is to just go into the delete.php file, and make an additional query before sending the “DELETE” query to your database. First run a select to get the src and tn_src, and just unlink($src), and unlink($tn_src). Here’s my code for delete.php:

        query($q1) or die(‘There was a problem retrieving information for this photo.’);
        if($return) {
        $data = $return->fetch_object();
        unlink($data->src);
        unlink($data->tn_src);
        }
        //Now that we have killed the actual files, get rid of the database entry
        $q2 = “DELETE FROM photos WHERE id=’$id’”;
        $result = $mysqli->query($q2) or die(‘There was a problem when deleting the photo information from the database.’);

        if($result) header(“location: index.php”);
        ?>

        I realize that doubling the number of times you communicate with a database is no way to make your application fast, but I think that’s the easiest and most fool-proof way to patch this functionality onto this tutorial, which – by the way – is awesome. Jeffrey Way is a BA.

    • owain Llewellyn

      Thanks for this great tutorial Jeff.. I know you hinted that you may add a album field to the database so that you can store the images in different albums at a later date…

      Do you have any idea when you might be looking at doing this? As I’d love to learn how to upload images into different categories and then select them via category in a dropdown or something similar.

      Im also getting the same errors as polymaze above… even though the functions seem to work correctly and the photos get added to the database.

      Any ideas?

    • http://www.flickr.com/photos/pkincses Peter

      Wow, don’t know how to thank you, been banging my head against the wall for a couple of days trying to call on images to be displayed.
      Thanks again.

    • Raman

      I was looking for something related to images for my next project and came across this tutorial. I am learning PHP, MySQL . With NETTUTS I think i can learn very fast and gain a solid hand in programming.

      Thanks for all the TUTS.

    • math1as

      First fo all great work, but I need some help please

      When uploading a Image I get:
      Warning: Cannot modify header information – headers already sent
      by (output started at C:\Program Files\xampp\htdocs\myphoto
      \database.php:1) in C:\Program Files\xampp\htdocs\myphoto
      \functions.php on line 99
      similar to polymaze owain Llewellyn

      Then there is a problem when uploading from other partitions of my HD

      Finally how can i adjust the maximum file size

      I hope someone can help me thanks

    • Terry

      can anyone tell me why i get this error?

      Fatal error: Cannot instantiate non-existent class: mysqli in /home/sites/eireloom.com/public_html/test/database.php on line 8

    • Terry

      Never mind Jeffrey was able to sort it out for me, thanks again Jeffrey!

    • Stephen

      I have learned a lot from this tutorial but I am banging my head against a brick wall now!

      I have tried to incorporate the “create dynamic thumbnails” tut files too, but each time I try to add an image nothing happens. The page refreshes, but nothing is added to the site or the database. I do not get an error message either. I am using localhost on a Vista machine.

      Any advice or pointers would be greatly appreciated.

      I would also like to add my vote to the security issue. I think security is paramount for any PHP script and advice/lines of code should be included with every tutorial as standard. I am a newbie to writing my own code, but I know PHP is open to exploitation by people who know what they are doing.

    • AdryDesign

      Awesome Thanks for share!! :D

      Great tutorial !!!

    • http://www.superdwayne.co.uk Dwayne Paisley-Marshall

      Did anyone else get an problem with the functions file?

    • Jake

      I am having a problem with the functions file to and really have no idea what is wrong it is saying: Fatal error: Function name must be a string in /…/…/…l/…/photo/functions.php on line 9

      This is a great tutorial I have learnt a lot too…Thanks!

    • MattyC

      Hi! looks like a perfect solution for my site, but i’m getting this message after uploading an image

      Success! Your file has been uploaded
      Fatal error: Call to undefined function imagecreatefromjpeg() in /Users/mattchinnock/Sites/photo/functions.php on line 74

      Can anyone help?

    • Ross

      I am having lots of issues with functions.php and thumbnails are not being created.
      “Success! Your file has been uploaded
      Warning: imagecreatefromjpeg(images/news.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in ”

      “Warning: imagesx(): supplied argument is not a valid Image resource”

      Any help would be greatly appreciated – getting different errors for gif uploads compared with jpeg files (getting maybe 8 errors for jpegs and only 2 for gif)

    • http://www.thejimgaudet.com/ Jim Gaudet

      Sorry so late, and I hope you don’t mind helping. (Also I hope I get an email response for replies, I see no option probably because I am already subscribed)

      I have everything working with 1 question. I want the user to be able to upload many files at once with multiple selects. I was hoping they could select their files like normal with a thumbnail preview (using windows explorer or whatever) and select multiple images to upload at once…

      Can you explain how I could adapt this project to allow uploading multiple images at once?

      Thanks,

    • Pingback: Web Design Industry Jargon: Glossary and Resources | How-To | Smashing Magazine

    • owca

      Write function adding multiple fields and as name use array fupload[]. Then just use their elements as single files.

      ie sth like this

      $photos_uploaded = $_FILES['fupload'];

      while( $counter <= count($photos_uploaded) )
      {
      and here the rest of the functions

    • Tim

      Hello,
      I have the same problem as polymaze.
      Is there someone that knows how to fix this.

      ————————————————————-
      //after uploading an image
      Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\TESTS\newPhotoSite_backend\database.php:1) in C:\xampp\htdocs\TESTS\newPhotoSite_backend\functions.php on line 99

      //after deleting an image
      Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\newPhotoSite_backend\database.php:1) in C:\xampp\htdocs\newPhotoSite_backend\delete.php on line 11

      The lines the error messages are listing target the ( header(”location: index.php”); ) line.

    • luke

      Please Help !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      hi this script is working perfect for me, i just have 1 problem…..

      i have created a login page just for me and it sends me to the upload a photo page..
      my upload form on the upload photo page, uploads the picture and sends it to the selected page for example. cats.php. but when i upload to cats.php the picture also gets sent to dogs.php and every other page…
      the reason i think it does this is because all pages have the getPhotos() function. please could any1 help me to change this so i can upload to different pages without the photo going to them all. please help

      thanks in advance for any1 who is smart enough to come up with the answer.

    • xtc2xl

      nice effect on vid, but for some reason just full of bugs when trying the source. good intro anyhow thnx

    • Thom

      hi would really appreciate it if someone could help, if people still replying.

      i have added a title field to the form which works and want to add 2 more for Country and Album name. What i would like is that when the image is uploaded instead of going just to the images folder the image goes to

      images/country/album_name/fullsized or tn – in response to what was inputed in the form

      and if the folder does not exist to create it – mkdir

      if anyone could help you would solve all my problems and i can get my site finished

      • Thom

        was having problems until i realised needed to use $_REQUEST to grab the form input. finally. wish i wasn’t a newbie to php, takes so long to figure things out, but getting there.

    • http://letsgetcool.com ibrahim benzer

      jeff i dont think it s a good idea to check for .jpg or .png in file name… the filename can be code.jpg.php
      why dont u check for the last “.” in the file name and control the filetype by that?

    • BBQ

      anyone got this thing working correctly ? I still can’t manage to get the images uploaded and thumbnails created :/

    • Spadez

      Great tutorial, but can the source code please be revised, as a lot of people are reporting the same errors out of the box and it isnt very helpful for newbies to be given code with errors, it takes us so long to figure out whats wrong.

    • Peter

      got it running but but when i upload an image it write to the database but does not upload the inage to the image folder not the thumb folder. I had a look at the code and i cant find any reference to the uploadPhoto.php file ..so should this not be referenced for it to upload to the files???

      • Arkad

        I would suggest you check the config file ‘$path_to_thumbs_directory = ‘images/tn/’;’ see it that folder exists

        otherwise it might be the sql code or database structure, hard to tell without being able to see the code

        ..good luck

    • Arkad

      Shot for the tutorial

      I’m pretty new to all this so I not sure if I am just missing something but it seems to me that in the code ( downloaded “source” ) in the functions.php page you have declared a variable that doesn’t exist anywhere.

      $mysqli_error – line 9

      although it is obvious that this is not a variable but a php defined function.
      just wondering if you do that on purpose

      I quite enjoy debugging it, I just figured you seem way to competent to make such a simple error. – or is used as a variable later or something?

      Not sure if anyone has pick up on this. Not a chance I am doing to read through all of the comments. will be very suprised if anyone even bothers to scroll down this far.. shouldn’t the most recent comments be displayed first?

      ORDER BY timestamp?

      very cool site though – like the random text thing you got going next to your logo on the footer
      “I don’t know how to put this but i’m kind of a big deal”

    • Pingback: new-impulse multimedia | Blog » Blog Archive » Webdesign vakjargon uitgelegd

    • Bozidar

      I need help to implement this php code into my html page…i succesfuly tested index.php on my wamp server but when i tried to implemnent code from index.php to my html he won’t create thumbs and show me this

      Please enter a description for your photo. ‘; if($filename == ” || !preg_match(‘/[.](jpg)|(gif)|(png)|(jpeg)$/’, $filename)) $error['no_file'] = ‘

      Please select an image, dummy!
      ‘; if(!$error) { move_uploaded_file($source, $target); $q = “INSERT into photo(description, src, tn_src) VALUES(‘$description’, ‘$src’, ‘$tn_src’)”; $result = $mysqli->query($q) or die(mysqli_error($mysqli)); if($result) { echo “Success! Your file has been uploaded”; } createThumbnail($filename); } // end preg_match } ?>

      i am new in web programing

    • Pingback: Żargon projektantów stron: słownik i źródła

    • David

      Warning: imagecreatefromjpeg(images/chroma.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in /home/u0051213827/public_html/blog/photo/functions.php on line 74

      Warning: imagesx(): supplied argument is not a valid Image resource in /home/u0051213827/public_html/blog/photo/functions.php on line 81

      Warning: imagesy(): supplied argument is not a valid Image resource in /home/u0051213827/public_html/blog/photo/functions.php on line 82

      Warning: Division by zero in /home/u0051213827/public_html/blog/photo/functions.php on line 85

      Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/u0051213827/public_html/blog/photo/functions.php on line 87

      Warning: imagecopyresized(): supplied argument is not a valid Image resource in /home/u0051213827/public_html/blog/photo/functions.php on line 89

      Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/u0051213827/public_html/blog/photo/functions.php on line 97

      Warning: Cannot modify header information – headers already sent by (output started at /home/u0051213827/public_html/blog/photo/index.php:32) in /home/u0051213827/public_html/blog/photo/functions.php on line 99

      any ideas? i dont geht it script dont work for me =( pls help

    • http://huriata.com Huroman

      The code seems awesome BUT don’t try to make it real, it has a lot of BUGS.

      1. It has problem with upload images (sometimes don’t load the image and thumbnail, Why? We do not know)

      2. “Delete function” delete the image from SQL but don’t eliminate the image in the folder who contains the image and the thumbnail.

      3. This example is good to understand how an admin works, but it’s far away to be useful.

    • Pingback: Web Design Industry Jargon: Glossary and Resources « RAMPAISARI

    • Pingback: Advance Level Php Tutorials and Scripts – Script tutorials

    • Pingback: Geek is a Lift-Style. » Web Design Industry Jargon: Glossary and Resources

    • James

      @ people reciving this error: “Warning: Cannot modify header information – headers already sent”

      I know this is a long undiccussed thread but I recieved this error a few times when I first worked this code into my site and the issue if I remember correctly was caused by my page forwarding line on submit. It had to do with conflicting with with one of the functions forwards or in script for references.

      I do have a question of my own and I know this is a long undiscussed thread but does anyone know how to scall the code up to accept multiple file uploads through say 5 file select fields?

    • Richie

      Great tutorial helped alot with a project am creating, just wondering if your going to do another tutorial this time using categories to organize the images thats what am having problems with

    • http://maranatha.tv JJ-DR

      Great tut, Jeffrey. I have been following this series of image uploading, and i have one question that really intrigues me.

      When using AJAX to edit text on the fly, you always tab off and the text is updated. My feeling is that once you click on any text to be edited, and you make changes to it, my first tendency is to hit the ENTER key. I think most web users have this tendency as the ENTER key usually captures the submit event, when in fact, there’s a submit or send button.

      I like the functionality of tabbing off or clicking away the text box once a change has been made. However, how can I also add the “onCLick ENTER” event to be the detected, and subsequently, the change to be reflected.

      Thanks a lot for this great series of tutorials.

    • Pingback: Q Simpel foto-album voor gebruikers-upload - 9lives - Games Forum