Setting up a simple page for wallpapers in your site

In this tutorial we will be showing you how to write a simple php wallpaper scripts and to showcase your collection of wallpappers in your website.

The idea is to write a php script to force a download for each image file because by default image files tends to open in a new browser window when clicked.

Instead of using a database,we will be using a single text file to track down all the download count of each wallpapper.

STEP 1 – HTML
The first step is to lay down the HTML markup for our wallpaper.We will be using just two image files for our tutorial.

demo.php

<div id="wallpaper">    	
  <div class="imagewrapper" style="float:left;">
     <img src="images/1.jpg">
        <form action="download.php" method="get">
	  <input type="text" hidden name="file" value="images/1.jpg">
	  <input type="text" hidden name="offset" value="0">
          <input type="submit" name="clicks" value="Download" >
        </form>
   </div> 

   <div  class="imagewrapper" style="float:right;">
      <img src="images/4.jpg">
         <form action="download.php" method="get">
	   <input type="text" hidden name="file" value="images/4.jpg">
           <input type="text" hidden name="offset" value="1">
           <input type="submit" name="clicks" value="Download" >
         </form> 
    </div>
</div>
       

The (download.php) is the script that forces the download and does the count,we will get to that later.Notice the use of the form element,you can substitute the form element with a link,the reason why we a using the form element is for better explanation.For example.

 <a href="download.phpfile=images/1.jpg&offset=0&clicks=Download">
Download</a>

STEP 2 – CSS
With the HTML markup in place, we can now concentrate on the presentation side of script. The CSS rules below target the wallpaper div by id (with the hash symbol), as it is present only once in the page, and the rest of the elements by class names.

style.css

    #wallpaper {
      margin:50px 250px;
      height:200px;
      padding:10px 10px 50px 10px;
      border:1px solid gray;
      border-radius:4px;
      }
   .imagewrapper img{
      max-width:250px;
      cursor:-webkit-zoom-in; 
      cursor:-moz-zoom-in;
      height:200px;
      }
   .imagewrapper{
      width:260px; 
      height:210px;
      display:block;
      position:relative;
      border:1px solid gray;
      padding:5px 0px 23px 10px;
      }
   .imagewrapper form{
      display:block;
      float:left;
      margin:5px 0px 5px 0px;
      }
   .imagewrapper form input{
      height:20px; 
      padding:1px 5px 8px 5px;
      width:100px;
     }


With the html and css in place we should have a page that looks like this

wallpaper_tuts

STEP 4 – PHP
As mentioned earlier this is where we force the image to dowload when a user clicks the input button and also where we count the number of time each image is download and save to a tile file. So here we go.

download.php

 if( isset($_GET['clicks']) )
 {
      
     $n=$_GET['offset'];
       
     if(!is_bot()){
      incrementClickCount($n);  
      }
 
     $file = $_GET['file'];

         function download_file( $fullPath ){

         // Must be fresh start
         if( headers_sent() )
         die('Headers Sent');

         // Required for some browsers
         if(ini_get('zlib.output_compression'))
         ini_set('zlib.output_compression', 'Off');

         // File Exists?
        if( file_exists($fullPath) ){

        // Parse Info / Get Extension
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);

           // Determine Content Type
            switch ($ext) {
            case "pdf": $ctype="application/pdf"; break;
            case "exe": $ctype="application/octet-stream"; break;
            case "zip": $ctype="application/zip"; break;
            case "doc": $ctype="application/msword"; break;
            case "xls": $ctype="application/vnd.ms-excel"; break;
            case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
            case "gif": $ctype="image/gif"; break;
            case "png": $ctype="image/png"; break;
            case "jpeg":
            case "jpg": $ctype="image/jpg"; break;
            default: $ctype="application/force-download";
            }

        header("Pragma: public"); // required
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false); // required for certain 
        //browsers
        header("Content-Type: $ctype");
        header("Content-Disposition: attachment; filename=\""
               .basename($fullPath)."\";" );        
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".$fsize);
	
       ob_clean();
       flush();
       readfile( $fullPath );

       } else
       die('File Not Found');

       }

  download_file($file);
 }


 function incrementClickCount($n)
 {   $h="getClickCount".$n;
    $count = $h() + 1;
	$lines = file('clickcount.txt');
	$result='';
	foreach($lines as $line_num=>$line) {
	if($line_num==$n){
	 $result.=$count."\n";
	}
	else{
	$result.=$line;}
	}
    file_put_contents("clickcount.txt", $result);
    
 }

 

 function is_bot()
 {
    /* This function will check whether the visitor is a search engine robot 'thanks to Martin Angelov'*/

    $botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
    "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
    "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
    "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
    "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
    "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
    "Mediapartners-Google", "Sogou web spider", "WebAlta",     
    "Crawler","TweetmemeBot",
    "Butterfly","Twitturls","Me.dium","Twiceler");

    foreach($botlist as $bot)
    {
        if(strpos($_SERVER['HTTP_USER_AGENT'],$bot)!==false)
        return true;	// Is a bot
    }

    return false;	// Not a bot
 }

Here is what we have just done the if isset($_SET[‘clicks’]) checks when the download button is clicked on demo.php file,if the button is clicked its executes two function,the download_file() which force the download of the image file and the incrementClickCount($n) which increase the download count by 1, but before this function is executed it checks if,by any chance, the visitor is a search engine robot scanning your links and not a real person.Robots are a good thing, as they get you included in services like Google Search, but in a situation such as this, can skew your download statistics. This is why the text file is updated only after the visitor passes the is_bot() validation.

Now the for the text file we have two function one that increase the download count by 1 already mentioned above and another function that display the count of each image file which looks like this.

   <?php function getClickCount0(){   
              $lines = file('clickcount.txt');
	      return $lines[0];
             }
         echo getClickCount0(); 
   ?>

This is how the text file is updated, in getClickCount0() the file() function returns each line of the text file as an array starting from 0,for example the above function will display the value that is in the first line of the text file only.So each line in the text file will represent the download count for each image.
Now the incrementClickCount($n) first of all executes the getClickCount0() to get the value of the first line of the text file,adds 1 to it,uses the file() function to separate each line of the text file as an array,use the offset parameter $n to locate the line of the text file we want to update,updates the line,and then rewrites the whole text file line by line exactly the same without merging the values of each separate line into a single line (! important).The $n parameter is used by the function to know which line of the text file to update.

Now we echo the getClickCount0() where we want the number count to be displayed in our demo.php file. In this case we display we want to display our count below each image. So our demo.php file will now look like this.

<div id="wallpaper">    	
  <div class="imagewrapper" style="float:left;">
     <img src="images/1.jpg" rel="zoom">
     <form action="demo7.php" method="get">
       <input type="text" hidden name="file" value="images/1.jpg">
       <input type="text" hidden name="offset" value="0">
       <input type="submit" value="Download" name="clicks" >
     </form>  
    <div class="count">
         <?php function getClickCount1(){   
               $lines = file('clickcount.txt');
	       return $lines[1];
               }
	       echo "<small><i><span style='color:#00bac4;'>"    
                     .getClickCount0()."</span>DownloadCount</i></small>"
         ?>     		  
									  
     </div>
   </div>
   <div  class="imagewrapper" style="float:right;">
      <img src="images/4.jpg" rel="zoom">
      <form action="demo7.php" method="get">
          <input type="text" hidden name="file" value="images/4.jpg">
          <input type="text" hidden name="offset" value="1">
          <input type="submit" value="Download" name="clicks" >
      </form>  
     <div class="count">
         <?php function getClickCount1(){   
               $lines = file('clickcount.txt');
	       return $lines[1];
               }
	       echo "<small><i><span style='color:#00bac4;'>"    
                    .getClickCount0()."</span>DownloadCount</i></small>"
         ?>     
      </div>
     </div>
</div>	 

Our demo.php should now look something like this.Please note that on the text file,make sure you start each lines of the file you are to use with 0 before the count can increase with every click and no space please.

wallpaper_tuts2

STEP 4 – Javascript
In other allow the users to preview each wallpaper before they decide to download,we include this javascript in the head section. The javascript enables the image to zoom in and out allowing the user to get a clearer view of the wallpaper. So include this javascript in the head section of the demo.php.For more on this javascript check out the github files.

<link href="style.css" rel="stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript" src="easing.js"></script>
<script type="text/javascript" src="smoothzoom.min.js"></script>
<script>
   $(window).load( function() {
    $('img').smoothZoom({
            });
       });
</script>

For the smoothzoom.min.js and easing.js files use the download button above.Please note, do not forget to include this attribute rel=”zoom” on the each image tag otherwise the javascript wont work.Also include the following into the style.css file because its is used by the javascript.

    /* this is used to style the div that displays the count */   
    .count{
          width:130px;
          display:block;
          float:right;
          margin:5px 0px 5px 5px;
          padding-left:10px;
          padding-right:6px;
          }

    /* Wrapper for image centering */
     #lightwrap {
         position:fixed;
         top:0;
         left:0;
         width:100%;
         height:100%;
         text-align:center;
         cursor:-webkit-zoom-out;
         cursor:-moz-zoom-out;
         z-index:999;
         }
    /* overlay covering website */
         #lightbg {
         position:fixed;
         display:none;
         top:0;
         left:0;
         width:100%;
         height:100%;
         background:rgba(255, 255, 255, .9);
	 z-index:998;
         }
    #lightwrap img {position:absolute;display:none;}
    #lightzoomed {opacity:0;}
    #off-screen {position: fixed;right:100%;opacity: 0;}

Conclusion
That all there is to this tutorial,least I forget include the demo.php file in the download.php file,this is to make sure that the the function
getClickCount0() inside the incrementClickCount($n) function is recongnized by the script engine. And we see the current stat of the count on page refresh,if you want to see real-time change of the count meter,you have to use jquery to make it work.
Also you can use as many image files as possible we are not limited to only two. If you have any question feel free to ask and if you have ideas on how to better improve this example do write something.
Thanks.