Wednesday, 12 February 2014

Thumbnail generating script for png,jpg,jpeg,gif for old & new versions of php

In this post  Iam explaining about a thumbnail generator script which can be used in your site. This script can be used to make thumbnails of jpeg,png & gif images. You can reduce to any thumbnail size that you prefer.
For doing it, Just copy the below code and name it as thumb.php. save this file in your project folder.
For generating thumb nail, you just want to do like this :-
 <img src="thumb.php?file=your_file_path&size=your_size">
For eg:
<img src="thumb.php?file=image.jpg&size=100">


<?php
ini_set('memory_limit','64M');
$site_config['document_root'] = $_SERVER['DOCUMENT_ROOT'];
$thumb_size = 128; //all thumbnails are this maximum width or height if not specified via get
$site_config['absolute_uri']=str_replace('///','//',str_replace('thumb.php?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI']));
$site_config['path_thumbnail']=$site_config['absolute_uri'].'/cache/images/';    //where to cache thumbnails on the server, relative to the DOCUMENT_ROOT
$image_error=$site_config['document_root'].$site_config['absolute_uri'].'/images/icons/image_error.png';    // used if no image could be found, or a gif image is specified

$thumb_size_x = 0;
$thumb_size_y = 0;

# Define quality of image
if (@$_GET["quality"]<>0) {
    $quality    = $_GET["quality"];
} else {
    $quality    = 80;
}

# Define size of image (maximum width or height)- if specified via get.
if (@$_GET["size"]<>0) {
    $thumb_size=intval($_GET["size"]);
}
if (intval(@$_GET["sizex"])>0)
{
    $thumb_size_x=intval($_GET["sizex"]);
    if (intval(@$_GET["sizey"])>0)
    {
        $thumb_size_y=intval($_GET["sizey"]);
    } else {
        $thumb_size_y=$thumb_size_x;
    }
}

if (file_exists($_GET['file']))
{
    $filename=$_GET['file'];
} else {
    $filename=str_replace('//','/',$site_config['document_root'].$site_config['absolute_uri'].'/'.$_GET["file"]);
}

# If calling an external image, remove document_root
if (substr_count($filename, "http://")>0)

{
    $filename=str_replace($site_config['document_root'].$site_config['absolute_uri'].'/','',$filename);
}

$filename=str_replace("\'","'",$filename);
$filename=rtrim($filename);
$filename=str_replace("//","/",$filename);
$fileextension=substr($filename, strrpos ($filename, ".") + 1);

$cache_file=str_replace('//','/',$site_config['document_root'].$site_config['path_thumbnail'].md5($filename.@$thumb_size.@$thumb_size_x.@$thumb_size_y.@$quality).'.'.$fileextension);

# remove cache thumbnail?
if (@$_GET['nocache']==1)
{
    if (file_exists($cache_file))
    {
        #remove the cached thumbnail
        unlink($cache_file);
    }
}

if ((file_exists($cache_file)) && (@filemtime($cache_file)>@filemtime($filename)))
{
    header('Content-type: image/'.$fileextension);
    header("Expires: Mon, 26 Jul 2030 05:00:00 GMT");   
    header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.'.$fileextension));
    echo (join('', file( $cache_file )));
    exit; # no need to create thumbnail - it already exists in the cache
}

# determine php and gd versions
$ver=intval(str_replace(".","",phpversion()));
if ($ver>=430)
{
    $gd_version=@gd_info();
}

# define the right function for the right image types
if (!$image_type_arr = @getimagesize($filename))
{
    header('Content-type: image/png');
    if(@$_GET['noerror'])
    {
        exit;
    } else {   
        echo (join('', file( $site_config['document_root'].$image_error )));
        exit;
    }
}
$image_type=$image_type_arr[2];

switch ($image_type)
{
    case 2: # JPG
        if (!$image = @imagecreatefromjpeg ($filename))
        {
            # not a valid jpeg file
            $image = imagecreatefrompng ($image_error);
            $file_type="png";
            if (file_exists($cache_file))
            {
                # remove the cached thumbnail
                unlink($cache_file);
            }
        }
        break;

    case 3: # PNG
        if (!$image = @imagecreatefrompng ($filename))
        {
            # not a valid png file
            $image = imagecreatefrompng ($image_error);
            $file_type="png";           
            if (file_exists($cache_file))
            {
                # remove the cached thumbnail
                unlink($cache_file);
            }
        }           
        break;

    case 1: # GIF
        if (!$image = @imagecreatefromgif ($filename))
        {
            # not a valid gif file
            $image = imagecreatefrompng ($image_error);
            $file_type="png";           
            if (file_exists($cache_file))
            {
                # remove the cached thumbnail
                unlink($cache_file);
            }
        }           
        break;
    default:
        $image = imagecreatefrompng($image_error);
        break;

}

# define size of original image   
$image_width = imagesx($image);
$image_height = imagesy($image);

# define size of the thumbnail   
if (@$thumb_size_x>0)
{
    # define images x AND y
    $thumb_width = $thumb_size_x;
    $factor = $image_width/$thumb_size_x;
    $thumb_height = intval($image_height / $factor);
    if ($thumb_height>$thumb_size_y)
    {
        $thumb_height = $thumb_size_y;
        $factor = $image_height/$thumb_size_y;
        $thumb_width = intval($image_width / $factor);
    }       
} else {
    # define images x OR y
    $thumb_width = $thumb_size;
    $factor = $image_width/$thumb_size;
    $thumb_height = intval($image_height / $factor);
    if ($thumb_height>$thumb_size)
    {
        $thumb_height = $thumb_size;
        $factor = $image_height/$thumb_size;
        $thumb_width = intval($image_width / $factor);
    }
}

# create the thumbnail
if ($image_width < 4000)    //no point in resampling images larger than 4000 pixels wide - too much server processing overhead - a resize is more economical
{
    if (substr_count(strtolower($gd_version['GD Version']), "2.")>0)
    {
        //GD 2.0
        $thumbnail = ImageCreateTrueColor($thumb_width, $thumb_height);
           $white = imagecolorallocate($thumbnail, 255, 255, 255);
   
        imagefilledrectangle($thumbnail, 0, 0,$thumb_width, $thumb_height, $white);
        imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
    } else {
        //GD 1.0
        $thumbnail = imagecreate($thumb_width, $thumb_height);
                   $white = imagecolorallocate($thumbnail, 255, 255, 255);
   
        imagefilledrectangle($thumbnail, 0, 0, $thumb_width, $thumb_height, $white);
        imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);           
    }   
} else {
    if (substr_count(strtolower($gd_version['GD Version']), "2.")>0)
    {
        # GD 2.0
        $thumbnail = ImageCreateTrueColor($thumb_width, $thumb_height);
                   $white = imagecolorallocate($thumbnail, 255, 255, 255);
   
        imagefilledrectangle($thumbnail, 0, 0, $thumb_width, $thumb_height, $white);
        imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
    } else {
        # GD 1.0
        $thumbnail = imagecreate($thumb_width, $thumb_height);
                   $white = imagecolorallocate($thumbnail, 255, 255, 255);
   
        imagefilledrectangle($thumbnail, 0, 0,$thumb_width, $thumb_height, $white);
        imagecopyresized($thumbnail, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $image_width, $image_height);
    }
}

# insert string
if (@$_GET['tag']<>"")
{
    $font=1;
    $string= $_GET['tag'];
    $white = imagecolorallocate ($thumbnail, 255, 255, 255);
    $black = imagecolorallocate ($thumbnail, 0, 0, 0);
    imagestring ($thumbnail, $font, 3, $thumb_height-9, $string, $white);
    imagestring ($thumbnail, $font, 2, $thumb_height-10, $string, $white);
}

switch ($image_type)
{
    case 2:    # JPG
        header('Content-type: image/jpeg');
        header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.jpeg'));
        @imagejpeg($thumbnail,$cache_file, $quality);
        imagejpeg($thumbnail,NULL,$quality);

        break;
    case 3: # PNG
        header('Content-type: image/png');
        header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.png'));
        @imagepng($thumbnail,$cache_file);
        imagepng($thumbnail);
        break;

    case 1:    # GIF
        if (function_exists('imagegif'))
        {
            header('Content-type: image/gif');
            header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.gif'));
            @imagegif($thumbnail,$cache_file);
            imagegif($thumbnail); 
        } else {
            header('Content-type: image/jpeg');
            header('Content-Disposition: inline; filename='.str_replace('/','',md5($filename.$thumb_size.$thumb_size_x.$thumb_size_y.$quality).'.jpg'));
            @imagejpeg($thumbnail,$cache_file);
            imagejpeg($thumbnail);
        }
        break;
}

//clear memory
imagedestroy ($image);
imagedestroy ($thumbnail);

?>

Wednesday, 15 January 2014

Redirecting a website to another website without changing the url

In this post Iam explaining how to redirect a website to another website without changing it's url.
For eg: If you have a domain named adidas.com. You want to redirect every page request of adidas.com  to nike.com.
Like adidas.com/aboutus.php should show the contents of nike.com/aboutus.php , but the url will remain as adidas.com/aboutus.php.

So Now I will explain how to acheive this. This can be acheived by CURL function in php.
Before doing this please ensure that you have access to both domains.& curl option is enabled in your server.

Here I will explain with an example.

First make a file named .htaccess

RewriteEngine On
RewriteRule index.html  index.php
RewriteRule Aboutus.html about.php
RewriteRule ContactUs.html  contact.php



Place above code in that .htaccess file.
Then create a file named index.php

<?php
getsite("targetsite/index.php");// Here give the target page from where to show the content

function getsite($url){
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// grab URL and pass it to the browser
$urlContent = curl_exec($ch);
$excont=str_replace('targetsite','yoursite',$urlContent);// Here replace the menu link with your sites

// Check if any error occured
if(!curl_errno($ch))
{
   $info = curl_getinfo($ch);
   header('Content-type: '.$info['content_type']);
   echo $excont;
}


// close cURL resource, and free up system resources
curl_close($ch);

}
?>

You have to create about.php,contact.php  similar to the above file by just changing the parameter in getsite function.
Hope it works.

Saturday, 4 January 2014

Integrating Google map in Websites Where users can Locate their places by a marker

When we create job websites,business directories.etc , situation will araise where we have to make users locate their Location inside a google map. In this modern era it has become an inevitable feautre where everyone uses google map for travelling & locating places.
So In this post I will try to explain how to include that in your php website.
Include this code in your header file :-
 <script type="text/javascript" src="map/jquery-1.4.4.min.js"></script>        
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBDvrqFePHOAvzk1bs2rsg309Pro20FhL0&sensor=false" type="text/javascript"></script>
    <script type="text/javascript" src="map/gmap3.js"></script> 
    <style>
      body{
        text-align:center;
      }
      .gmap3{
        margin: 20px auto;
        border: 1px dashed #C0C0C0;
        width: 500px;
        height: 500px;
      }
    </style>
    
    <script type="text/javascript">
      $(function(){
      
        $("#test").gmap3({
          marker:{
            latLng: [23.00,54.00],
            options:{
              draggable:true
            },
            events:{
              dragend: function(marker){
                $(this).gmap3({
                  getaddress:{
                    latLng:marker.getPosition(),
                    callback:function(results){
                      var map = $(this).gmap3("get"),
                        infowindow = $(this).gmap3({get:"infowindow"}),
                        content = results && results[1] ? results && results[1].formatted_address : "no address";
                      if (infowindow){
                        var lat = marker.getPosition().lat();
                        var lng = marker.getPosition().lng();

                        infowindow.open(map, marker);
                        infowindow.setContent(content+lat+lng);
                        var userdat=content+'&'+lat+'&'+lng;
                      $.post("getmapdata.php", {userdat: userdat}, function(data){
    alert("Google map Location successfully updated: "+data);
});
                      } else {
                        $(this).gmap3({
                          infowindow:{
                            anchor:marker, 
                            options:{content: content}

                          }
                        });
                      }
                    }
                  }
                });
              }
            }
          },
          map:{
            options:{
              zoom: 8
            }
          }
        });
        
      });
    </script>
Here in the above script we can see some included scripts. jquery-1.4.4.min.js can be downloaded from jquery.com site.
Second script included is directly from google source so we didn't have to worry about it.
Third script included is gmap3.js. We have to download it from http://gmap3.net/
Now we have done the basic settings, now it requires only to include map in our page.

<div class="map">
<div id="test" class="gmap3"></div>
   <p> Drag the marker to point to an address</p>
</div>

Now execute the page we can see the map coming in that area.
Now we have to do is to save the latitude ,longitude & location corresponding to the users dragging the mouse.Look at this portion of above code:-
var userdat=content+'&'+lat+'&'+lng;
                      $.post("getmapdata.php", {userdat: userdat}, function(data){
    alert("Google map Location successfully updated: "+data);

Here the data is saved in the getmapdata.php  php file. So our next step is to create that file:-
<?php
session_start();
include("db.php");
if(isset($_SESSION['user_uni'])){
$user=$_SESSION['user_uni'];
}
$fd=$_POST['userdat'];
$fdarr=explode('&',$fd);
$location=$fdarr[0];
$lat=$fdarr[1];
$long=$fdarr[2];
mysql_query("Update tblprofile set location='$location',latitude='$lat',longitude='$long' where login_id='$user'") or die('Error1:'.mysql_error());

?>
Here data will be saved in the table. I have used a demo code, change according to your project. So now  we will get a map similar to this:

Here In above map user have to drag that marker to their location and that location's latitude and longitude will be automatically saved into the database



Thursday, 2 January 2014

Redirecting Virtual urls like subdomain names to a subfolder using htaccess file

Here I will explain how to redirect virtual urls similar to subdomain names to a subfolder using .htaccess file.
I will explain it with the help of an example.Iam working on a project named blogger.com.
. Here users can create their own blog urls..  if users name is robert. He can create a url like robert.blogger.com. Here actually we are not creating subdomains manually. If we create so then we have to do it manually for all users.that will go out of control. so what I do is created a folder named user where all requests will execute & it act as a subdomain. Here I wrote this code for htaccess.just try it..


Options +FollowSymLinks
RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.blogger.com
RewriteCond %{HTTP_HOST} ([^.]+)\.blogger.com
RewriteRule ^(.*) user/user.php?username=%1


IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti*

<Limit GET POST>
order deny,allow
deny from all
allow from all
</Limit>
<Limit PUT DELETE>
order deny,allow
deny from all
</Limit>
AuthName blogger.com



Thursday, 10 October 2013

Uploader class for cakephp

In this Post Iam writing code for uploading files in cakephp....

Create Uploader.php in Model folder & paste below code :-
<?php
 class Uploader extends AppModel
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
        
        function setDir($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }
        
        function allowAllFormats(){
            $this->allowAll =   true;
        }
        
        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }
        
        function setExtensions($options){
            $this->extensions   =   $options;
        }
        
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
        function getExtension($string){
            $ext = "";
            try{
                    $parts = explode(".",$string);
                    $ext = strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext = "";
            }
            return $ext;
}
        
        function setMessage($message){
            $this->errorMessage =   $message;
        }
        
        function getMessage(){
            return $this->errorMessage;
        }
        
        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
$this->imageSeq = $seq;
}

function getRandom(){
return strtotime(date('Y-m-d H:i:s')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
        function uploadFile($fileBrowse){ 
            $result =   false;
$size   =  $fileBrowse["size"];
            $name   =  $fileBrowse["name"];
            //$size   =   $_FILES[$fileBrowse]["size"];
            //$name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
                
if($this->sameName==false){
                $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
$this->uploadName= $name;
}
                if(move_uploaded_file($fileBrowse["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }
        
        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }
        
    }  ?>

Now I will explain how to use it..

In the controller file include Uploder model in the $uses array.

the...
if the View file code is like this:-

<form name="fileform" method="post" action="<?php echo $urlRoot; ?>image/add"/>
<input type="file" name="txtFile"/>

</form>
Now  create folder media and then add index to core.php
Configure::write('MediaDir',dirname(dirname(__FILE__)).'/media/');

Now in controller folder,code like this

if(!empty($_FILES['txtFile']['name'])){ 
$mediaBaseDir = Configure::read('MediaDir');//Media Base Directory//created outside root folder,path set in the core.php
if(!is_dir($mediaBaseDir.'news')){
mkdir($mediaBaseDir.'news');
chmod($mediaBaseDir.'news',0777);
}
$mediaPath = $mediaBaseDir.'news'.'/';
$this->Uploader->setDir($mediaPath);
$this->Uploader->setExtensions(array('jpg','jpeg','png','gif'));
$this->Uploader->setMaxSize(.8);
$this->Uploader->setSequence('news'); 
$filename = $_FILES['txtFile'];
if($this->Uploader->uploadFile($filename)){ //upload success
$image = $this->Uploader->getUploadName();

}
}



Tuesday, 1 October 2013

Integrating album gallery in a wordpress site

In this post Iam explaining about integrating a new album gallery named Grand photo gallery plugin.
Download that plugin from: http://wordpress.org/plugins/flash-album-gallery/installation/

  1. Upload the files to 'wp-content/plugins/flash-album-gallery'.
  2. Activate the plugin.
  3. Be sure that after activation 'wp-content/plugins/flagallery-skins' folder (chmod 755) created successfully. If not, create it manually and install skins through admin Skins page or via ftp.
  4. Add a gallery and upload some images (the main gallery folder must have write permission).
  5. Go to your post/page an enter the tag '[flagallery gid=X]', where X - gallery IDs separated by comma. Easy way is click FlAGallery button on the Editor panel.
  6. If you would like to use additional Skins (only a option), go to Skins, download the skin and upload the file through Skins page in WordPress admin panel.
Steps

Add Gallery

The first thing you will want to do is upload some images. Before you can do that, you have to create a gallery. You do that on the Manage Galleries -> Add Gallery tab. Galleries are created below the path specified on the General Options page, typically wp-content/flagallery/. Creating a gallery actually creates a new folder on the server to store the images.

Adding Images

Once you’ve created a gallery you can add images to it. There are two different ways to add images to a gallery, by uploading them and by copying them to a location and then scanning the directory.
Note that when uploading images, check that the php.ini file for your server sets the maximum file upload size high enough.
Upload images one or more at a time. This is done from the Upload Images tab on the Manage Galleries page. You can select multiple files to upload and see progress of each image as it is being uploaded.

Managing Images

Once you get images into a gallery, you can perform a number of different operations on them. Probably the first thing you’ll want to do is to annotate them. While you’re at it you may as well add a description to your gallery.

Add Skins

Skin Options.
Each skin has its own set of properties. To change these properties, there is a control panel (Click to Active Skin Options or Options)

Add Gallery to Page / Post

add like 
<?php echo do_shortcode( '[flagallery gid=all name="Gallery"]' ); ?>

f you use gid=all:
[flagallery gid=all name="Gallery" orderby=title order=ASC excluude=3,5]

This shortcode will display all galleries (except ID=3 and ID=5) sorted by title, ASC order.
Wanna display only three galleries in specific order? No problem:
[flagallery gid=4,2,5 name="Gallery"]

Tuesday, 3 September 2013

Encryption & Decryption class for PHP projects

In this Post Iam explaining about encryption & decryption class which can be used in php projects. In most of projects php developers will use only built in encryption techniques like base64_encode,sha1,md5.etc.
But in the class which iam providing uses most  encryption algorithms to generate code & also uses most Decryption algorithms to decrypt the code...

Here is the code:-

Copy the code and create new file named Crypt.php and save it in your library folder.

<?php

class Crypt {

var $keys;
function crypt_key($ckey){
$this->keys = array();
$c_key = base64_encode(sha1(md5($ckey)));
$c_key = substr($c_key, 0, round(ord($ckey{0})/5));
$c2_key = base64_encode(md5(sha1($ckey)));
$last = strlen($ckey) - 1;
$c2_key = substr($c2_key, 1, round(ord($ckey{$last})/7));
$c3_key = base64_encode(sha1(md5($c_key).md5($c2_key)));
$mid = round($last/2);
$c3_key = substr($c3_key, 1, round(ord($ckey{$mid})/9));
$c_key = $c_key.$c2_key.$c3_key;
$c_key = base64_encode($c_key);
for($i = 0; $i < strlen($c_key); $i++){
$this->keys[] = $c_key[$i];
}
}
function encrypt($string){
$string = base64_encode($string);
$keys = $this->keys;
for($i = 0; $i < strlen($string); $i++){
$id = $i % count($keys);
$ord = ord($string{$i});
$ord = $ord OR ord($keys[$id]);
$id++;
$ord = $ord AND ord($keys[$id]);
$id++;
$ord = $ord XOR ord($keys[$id]);
$id++;
$ord = $ord + ord($keys[$id]);
$string{$i} = chr($ord);
}
return base64_encode($string);
}
function decrypt($string){
$string = base64_decode($string);
$keys = $this->keys;
for($i = 0; $i < strlen($string); $i++){
$id = $i % count($keys);
$ord = ord($string{$i});
$ord = $ord XOR ord($keys[$id]);
$id++;
$ord = $ord AND ord($keys[$id]);
$id++;
$ord = $ord OR ord($keys[$id]);
$id++;
$ord = $ord - ord($keys[$id]);
$string{$i} = chr($ord);
}
return base64_decode($string);
}
}

?>

For decrypting the code we need a pass key also.
So if you want to use it you have to insert a demo login credintials like:-
Password: n6S+5LmuiXY=
Passkey: 6138880

So after login check the databse corresponding to this username. Fetch the passkey for corresponding data row.
Pass this passkey to the Crypt_key() function.. After that it will call encrypt function, so it will encrypt the corresponding string using that passkey...

eg:  $query = "SELECT * FROM `cms_auth` WHERE `username`='".$username)."' ";
$rec = $this->fetchAll($query);
                 $this->passKey = $rec[0]["pass_key"];
$crypt = new Crypt();
$crypt->crypt_key($this->passKey);
$password = $crypt->encrypt($this->password);

Generating PDF report using PHP

While creating large projects like school portals,realestate portals.etc. , we need to generate reports in pdf format.So In this Post Iam explaing how to generate pdf reports....

For this we have to download pdf library named TCPDF.
download it from http://www.tcpdf.org/

Include it in your project.

I will explain it with an example..

In my project i have to give attendance report of students in pdf.

Step 1: Fetched data from database and  generated a text file.
Step 2: Created PDF file from that text file.

Code for generating Text file

    <?php
$student=$_SESSION['loggedstudent'];
$atd=new Attendance();
$stddet=$atd->getstudentthreaddetails($student);
$ses=new Sess();
$nam="Report-";
$nam.=substr(md5(rand(1111,9999)),0,8);
$nam.=strtotime(date("Y-m-d H:i:s"));


  $k=0;  
 $file=fopen("reports/".$nam.".txt","w+"); 
fclose($file);
    for($i=0;$i<count($stddet);$i++){    
$threadid=$stddet[$i]['thread_id'];
$det=$atd->getthreaddetails($threadid);
$k=$k+1;



  $file=fopen("reports/".$nam.".txt","a"); 
$data1=$det[0]['date_attendance'].";";
fwrite($file, $data1);
fclose($file);
$dat= $det[0]['date_attendance'];

if(isset($_SESSION['atti'][$dat])){
 $_SESSION['atti'][$dat]['sess'.$i]=$det[0]['session'];
}else{

$_SESSION['atti'][$dat]=$det[0]['session'];
}

$ds=explode('-',$dat);
$month=$ds[1];
  $file=fopen("reports/".$nam.".txt","a"); 
  switch ($month) {
  case '1':
   $data="January".";";
    break;
  
  case '2':

 $data="February".";";
case '3':
  
     $data="March".";";
    break;
  
  case '4':

    $data="April".";";
case '5':

     $data="May".";";
    break;
  
  case '6':
    $data="June".";";
 break;

case '7':

    $data="July".";";
    break;
  
  case '8':

    $data="August".";";

  break;

case '9':
   
    $data="September".";";
    break;
  
  case '10':
   $data="October".";";

break;

  case '11':
     $data="November".";";

break;

  case '12':

    $data="December".";";
break;


}
fwrite($file, $data);
fclose($file);

 $file=fopen("reports/".$nam.".txt","a");    
$sesid= $det[0]['session_id'];
$sesdet=$ses->getcommunitydetails($sesid);
$data2=$sesdet[0]['session_name'].PHP_EOL;
fwrite($file, $data2);
fclose($file);


}
 $cou= count($_SESSION['atti']); 
unset($_SESSION['atti']);
$file=fopen("reports/".$nam.".txt","a");
$data4="Leaves(Sessions):".$k.";";
fwrite($file, $data4);
fclose($file);
$file=fopen("reports/".$nam.".txt","a");
$data12="Leaves(Days):".$cou.";";
fwrite($file, $data12);
fclose($file);
header("Location:attendancetopdf.php?fl=".$nam."&std=".$student."&hash=".md5(rand(0,5000)));
?>

2) Creating PDF  file


<?php
$nam=$_GET['fl'];
$std=$_GET['std'];
ob_start();
session_start();
include("autoload.php");
$db     =   new MySql();
$db->connect();

$st=new Student();
$stddet=$st->getdetails($std);

$cr=new Branch();
 $yr=new Year();
 $div=new Division();
 $ac=new Academic();
 $fac=new Faculty();
$crseid= $stddet[0]['branch'];
$crdet=$cr->getcommunitydetails($crseid);
$branchname= $crdet[0]['branch'];
                 
                  $crseid= $stddet[0]['year'];
$crdet=$yr->getcommunitydetails($crseid);
$yearname= $crdet[0]['year'];
                 
                    $crseid= $stddet[0]['div'];
$crdet=$div->getcommunitydetails($crseid);
$divisionname= $crdet[0]['div'];
                 
                  $crseid= $stddet[0]['academic'];
$crdet=$ac->getcommunitydetails($crseid);
$academicname= $crdet[0]['year'];
  



// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// extend TCPF with custom functions
class MYPDF extends TCPDF {

  // Load table data from file
  public function LoadData($file) {
    // Read file lines
    $lines = file($file);
    $data = array();
    foreach($lines as $line) {
      $data[] = explode(';', chop($line));
    }
    return $data;
  }

  // Colored table
  public function ColoredTable($header,$data) {
    // Colors, line width and bold font
    $this->SetFillColor(255, 0, 0);
    $this->SetTextColor(255);
    $this->SetDrawColor(128, 0, 0);
    $this->SetLineWidth(0.3);
    $this->SetFont('', 'B');
    // Header
    $w = array(40, 35, 40, 45);
    $num_headers = count($header);
    for($i = 0; $i < $num_headers; ++$i) {
      $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
    }
    $this->Ln();
    // Color and font restoration
    $this->SetFillColor(224, 235, 255);
    $this->SetTextColor(0);
    $this->SetFont('');
    // Data
    $fill = 0;
    foreach($data as $row) {
      $this->Cell($w[0], 6, $row[0], 'LR', 0, 'L', $fill);
      $this->Cell($w[1], 6, $row[1], 'LR', 0, 'L', $fill);
      $this->Cell($w[2], 6, $row[2], 'LR', 0, 'R', $fill);
   
      $this->Ln();
      $fill=!$fill;
    }
    $this->Cell(array_sum($w), 0, '', 'T');
  }
}

// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('');
$pdf->SetTitle('Attendance Report');
$pdf->SetSubject('Report');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$headertitle="Attendence Report";
$headerstring.="Name:  ".$stddet[0]['fname']." ".$stddet[0]['lname'].PHP_EOL;
$headerstring.="Reg no:  ".$stddet[0]['regno'].PHP_EOL;
$headerstring.="Roll no:  ".$stddet[0]['rollno'].PHP_EOL;
$headerstring.="Email:  ".$stddet[0]['email'].PHP_EOL;
$headerstring.="Mobile:  ".$stddet[0]['contact_mobile'].PHP_EOL;
$headerstring.="Branch:  ".$branchname.PHP_EOL;
$headerstring.="Year:  ".$yearname.PHP_EOL;
$headerstring.="Division:  ".$divisionname.PHP_EOL;
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $headertitle,$headerstring);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$marg="55px";
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, $marg, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
  require_once(dirname(__FILE__).'/lang/eng.php');
  $pdf->setLanguageArray($l);
}

// ---------------------------------------------------------

// set font
$pdf->SetFont('helvetica', '', 12);

// add a page
$pdf->AddPage();

// column titles
$header = array('Leave date', 'Month', 'Session');

// data loading
$data = $pdf->LoadData('reports/'.$nam.'.txt');

// print colored table
$pdf->ColoredTable($header, $data);

// ---------------------------------------------------------

// close and output PDF document
$pdf->Output('attendancetopdf.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================+
unlink('reports/'.$nam.'.txt');// deleting local file
?>

Now generated pdf file will be generated in new window.

Simple class for Uploading Files in PHP

Everyone is familiar with uploading files in php. While uploading files we have to deal with many things like , we have to check whether corresponding file format is valid, uploaded file exceed maximum size, giving specified name for files.etc. So here iam giving various functions within a class which can help you during your file uploading operation.
Copy the below code and paste it  in a file named Uploader.php and include in your library folder.
<?php

    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
private $seqnence;
        
        function __construct($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }
        
        function allowAllFormats(){
            $this->allowAll =   true;
        }
        
        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }
        
        function setExtensions($options){
            $this->extensions   =   $options;
        }
        
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
        function getExtension($string){
            $ext = "";
            try{
                    $parts = explode(".",$string);
                    $ext = strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext = "";
            }
            return $ext;
}
        
        function setMessage($message){
            $this->errorMessage =   $message;
        }
        
        function getMessage(){
            return $this->errorMessage;
        }
        
        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
$this->imageSeq = $seq;
}
function sameName($true){
$this->sameName = $true;
}
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
                $util   =   new Utilities();
if($this->sameName==false){
                $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$util->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
$this->uploadName= $name;
}
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }
        function uploadmultiFile($name,$size,$tmpname){
            $result =   false;
            $size   =   $size;
            $name   =   $name;
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
                $util   =   new Utilities();
        if($this->sameName==false){
                    $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$util->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
            $this->uploadName=  $name;
        }
                if(move_uploaded_file($tmpname,$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }
        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }
        
        
    }

?>

USING Uploader.php class in Your Project

Consider you have a form like this:-
<form name="upload" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="txtFile"  size="40"/>
<input type="submit" name="submit"/>
</form>

After submitting the Image file, in the upload.php get the image file like this :-

   $absDirName =   dirname(dirname(__FILE__)).'/uploads';
            $relDirName =   '../uploads';
         $uploader   =   new Uploader($absDirName.'/');//set the target directory
            $uploader->setExtensions(array('jpg','jpeg','png','gif'));// setting the extension
            $uploader->setSequence('img');// setting image sequence
            $uploader->setMaxSize(10);// setting size limit
            if($uploader->uploadFile("txtFile")){
                 $image     =   $uploader->getUploadName(); //get uploaded image name
                }