Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   How to Make Image Gallery in PHP with AJAX and Light-box (http://www.go4expert.com/articles/image-gallery-php-ajax-light-box-t24272/)

ManzZup 26Dec2010 21:49

How to Make Image Gallery in PHP with AJAX and Light-box
 
Article is about making a simple yet powerful Gallery system using PHP, AJAX and Lightbox

Background



Some days ago i started ma new project im building our site (for the 4th time) :D Thought to do a real difference so everything i needed to code by me. Hope this will help you too.

The Code



http://imgs.g4estatic.com/php-based-...llery/gal2.jpg

Let's get started.

Steps:
  1. Make a simple php script that can retrieve the records about images from the database and do the dynamic page breaking.
  2. Adding the lightbox to have a little show off :D
  3. Adding the AJAX part
PHP script

First thing we need is to make a php script that can retrieve all the records about the images and do page breaking. Here i used to store the info in a database rather than reading directly from a folder. This makes it possible for me to add an image description. So, when i retrieve the images possibly i want to do the dynamic page breaking, adding the pages automatically so there's no mess there.

First make a folder name "res" and add some pics to it.

Then in your database make a new table "images"

Add 3 fields,
*ID [auto increment],
*Img - path to the image
*Desc - Description of the image

After add some record to it

I added 10 for the testing purposes

Now the php script

Make a file named view.php

NOTE: I have used CSS styling here so be patient to see the CSS style after this code :D

[view.php]
PHP Code:


<?php

$start 
1;     // This is the variable that stores the current page of the gallery. Default its set to 1 to prevent errors

$page_name "view.php"//The name if added to make things easier

if(isset($_GET['q']))$start $_GET['q']; //Check weather a variable is passed to page, if so it become the current page number.

$limit 5;  //Number of pictures that should be shown per page
$eu = (($start-1) * $limit);  //Get the offset to be used in Mysql query, dont bother about it :D

$conn mysql_connect(db_host,db_user,db_pwd);   //Connecting to the databse, put the necessary variables. Ex: db_host replace with "127.0.0.1"

if(!($conn)) echo "Failed To Connect To The Database!";
else{
    
    if(
mysql_select_db(db_name,$conn)){  //Check weather databse exists

//From here we first do the page breaking as it takes the big deal of the script

    
$no mysql_num_rows(mysql_query("SELECT * FROM images")); //Count number of rows

    
$max ceil($no/$limit);  //Divide it by the limit and round off to detemine the number of pages


$nav "";    //This variable determines the pages
    
for($page 1$page <= $max$page++)   //Loop to get the pages
{
   if (
$page == $start)
   {
      
$nav .= "<span class=\"sel\"> $page </span>"// no need to create a link if the start page == current page
   
}
   else
   {
      
$nav .= " <a href=\"$page_name?q=$page\">$page</a> "//Else add the page number, here the link of <a href> is the same page passed with argument of page number ('q')

   

}
if(
$start 1){     //Above codes make a complete thing but its rather good to add these, the professional features. This add [Prev] and [First].

    
$page $start 1;
    
$prev " <a href=\"$page_name?q=$page\">[Prev]</a> ";
    
$first " <a href=\"$page_name?q=1\" \">[First]</a> ";
}else{
    
$prev  '&nbsp;';
    
$first  '&nbsp;';
}

if(
$start $max){   //This adds the [Next] and [Last] i think the code is pretty understandable.
    
$page $start +1;
    
$next " <a href=\"$page_name?q=$page\">[Next]</a> ";
    
$last " <a href=\"$page_name?q=$max\">[Last]</a> ";
}else{
    
$next  '&nbsp;';
    
$last  '&nbsp;';
}

echo 
"<div id=\"nav\">".$first$prev$nav$next$last."</div>";  //Now we write the navigation bar.
echo "<br />";

//Right. Heyy what about the images?? Ohh :D here it comes

    
$result mysql_query("SELECT * FROM images LIMIT $eu,$limit");
//In the above query the records are called from a specific no of records($limit) starting by a specified point($eu) ex: "SELECT * FROM images LIMIT 10,20" is thats what passed, Mysql will return records starting from the 10th records (including 10th) another 20 mean 10-39. This way page breaking is pretty simple :D



    
while($rows mysql_fetch_array($result)){
        
$img $rows['Img'];       //get the img URL
        
$test getimagesize($img); //This is optional but you may need
        
$desc "Description :" .$rows['Desc']. "<br />".
                
"File Name :" .basename($img) ."<br />"
                
"Diemensions :" .$test[0]. "x" .$test[1]. "<br />".
                
"File Size :" .ceil(filesize($img)/1024). "KB";
                 
//Above whole of it was about makign a nice description of the image.

        
echo "<a href=\"".$img."\" rel=\"lightbox[gal]\" title=\"".$desc."\"><img src=\"" .$img"\"/></a>";
               
//Add the images, looping though the records
               //AURAH! php done :D
    
}
    
    
   }    
}

?>

Just dont run before adding the CSS style

[style.css]
HTML Code:

img{
        height:25%;
    padding:10px;
        border:2px solid #666;
        margin:5px;
}

#nav{
        left:0;
        text-align:center;
        font-family:"calibri";
        font-size:18px;
        text-decoration:none
}
#nav .sel{font-size:22px}

A:link,A:visited,A:active, A:hover { text-decoration: none; color:#333}

And add this to attach the CSS style Add to the bottom of view.php
.....
?>
HTML Code:

<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
</html>

Now you'll see a pretty much good :D gallery.

Adding lightbox

Light box is a very attrtactive feature used in many things today. In the code above you'll notice that the <img /> tag is full of other things which of course related to the lightbox. So first Download Lightbox.

Now extract all the directory where you have the view.php but DONT extract the index.html.

Now we have to do the linking of the Lightbox.

Modify the HTML code like this:
HTML Code:

<html>
<head>
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<link href="style.css" rel="stylesheet" type="text/css">
</head>
</html>


Now you click on images and SEE A WONDER :DD

Adding AJAX

AJAX(Asynchronous JavaScript and XML_) is an attractive technology ijmplemented by many popular sites.

ex: in facebook the images load when browsing a Gallery without loading pages seperately. This allows easy navigation to the user. Adding AJAX is pretty much simple in our case.

Make a new file called inidex.php

This is the page that user first sees

Heres the code for it

[index.php]
PHP Code:

<html>
<
head>
<
title>My Gallery</title>

<
script type="text/javascript">
function 
init(){
    
view(1);
}
function 
view(no){

xmlhttp = new XMLHttpRequest();  //Make a new XML request. It is used to send the AJAX requests.
xmlhttp.onreadystatechange=function() //This function retrieves the response from the page and shows it in the content area

  
{
  if (
xmlhttp.readyState==&& xmlhttp.status==200)
    {
    
document.getElementById("load_area").innerHTML=xmlhttp.responseText;
    }else{
        
document.getElementById("load_area").innerHTML "Loading please wait ....";
    }
  }
    
xmlhttp.open("GET","view.php?q="+no,true); //Here the resource path is view.php we made before. But now we have to adjust the code of view.php to suit with AJAX

    
xmlhttp.send();
}
      
window.onload init;  //At loading we load the 1st set of images to prevent errors
</script>

<!-- the Lightbox part should be added to this -->
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<link href="style.css" rel="stylesheet" type="text/css">

</head>
<div id="load_area">
</div>
</html> 

Here's how the view.php should be edited

[view.php]
PHP Code:


...
.
.

else
   {
      
$nav .= " <a href=\"#$page\" onClick=\"view($page)\">$page</a> "//Note that Onclick event is added to call the javascript function when the link is clicked

   

...
..
    
$prev " <a href=\"#$page\" onClick=\"view($page)\">[Prev]</a> ";
    
$first " <a href=\"#1\" onClick=\"view(1)\">[First]</a> ";
...
.
..
     
$next " <a href=\"#$page\" onClick=\"view($page)\">[Next]</a> ";
     
$last " <a href=\"#$max\" onClick=\"view($max)\">[Last]</a> ";
..
.. 

in style.css
img{ replaced with #load_area img{

VIOLAAAAAHH!!!!!
DONE it

You'have sucessfully made an Ajax+Lightbox+php Gallery

Alter things to make it more attractive.

http://imgs.g4estatic.com/php-based-...llery/gall.jpg

http://imgs.g4estatic.com/php-based-...lery/gal21.jpg

keyideas 29Jul2011 15:35

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
Hello ManzZup,

You have share a very useful tips to me. I was really searching this script as I developing an image gallery where this script is to used.

Thanks,

ManzZup 29Jul2011 20:58

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
your welcome :)
please ask for any other details

eBiz 30Jul2011 10:09

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
Thanks a lot.
For this knowledge.

I have not tried. But I think there must be certain benefits in the future.

adammarleymtts 1Aug2011 10:43

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
Wow this is a great post. And this is very interesting and useful. I would like to work on this. Thanks for sharing it with us.

ManzZup 1Aug2011 15:37

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
thank you guys :)

neerjasoftwares 19Oct2011 12:06

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
With following through your beneficail advice, I started using it but I am having a little bit problem in doing so. Some images are showing up in one browser but some got blind in the other. As you can see my Services page, where I used some of the images
Please sir help me for this at the earliest....In need of your reply at the urgent.

ManzZup 19Oct2011 20:16

Re: How to Make Image Gallery in PHP with AJAX and Light-box
 
i think you would be receiving problems with some older browsers [specially IE6/7] but i have tested on most of the newer ones without any prblem
can you direct me a link to check up the problem and state the browsers you were testing this on?


All times are GMT +5.5. The time now is 18:23.