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
                }