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
                }






Saturday, 31 August 2013

Easy way of calling classes in Core PHP

When we do large projects, we did have lot of class libraries associated with our project. So whenever we want to use a class in our code page, You have to include that class in the top of the page.
But rather than this php has given an easy way to do this named    _autoload(); function...

Below Iam giving code for this:-

<?php

date_default_timezone_set("Asia/Calcutta");
define("CONST_BASEDIR",dirname(__FILE__));
define('CONST_LIBRARY_FOLDER',CONST_BASEDIR.'/libs');// class files placed folder
$_SESSION['CONST_BASEDIR']=CONST_BASEDIR;
error_reporting(E_ALL & ~ E_NOTICE);
function __autoload($className){

if(!class_exists($className)){
$parts = explode("_",$className);
if(count($parts)==1){
$folder = CONST_LIBRARY_FOLDER."/".$className.".php";
}else{
$folder = CONST_LIBRARY_FOLDER."/";
for($i=0;$i<count($parts)-1;$i++){
$folder.= strtolower($parts[$i]);
$folder.="/";
}
$folder.=$parts[count($parts)-1].".php";

}
include_once($folder);
}
}
?>
Just save the above page as autoload.php and include in every page.

So after that You didn't want to include any class seperately, you just want to call corresponding class like


$obj=new User();//creating object

$userdetails=$obj->getdetails();// calling function with class object


So when doing this automatically _autoload function will look into the libraray folder for User.php file and it will include it.... and will works fine...............................

Tuesday, 30 July 2013

Fetching RSS feed from a site using PHP

In some projects their araise situation like you have to fetch Rss feeds from another site.. so for this In PHP5 we have DOM extension which make it easy to work with XML documents. so below am writing code to do that... 

For getting demo,replace the url with the url you want to fetch... In case of local languages mention their encoding in html header..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>rss feed</title>
</head>
<?php
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array ( 
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 5;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>
<body>
</body>
</html>

Friday, 28 June 2013

Extracting data from Excel file using PHP

When we are doing large projects,their may arise situation like we have to import data to our database from Excel sheets. This is a basic requirement which is asked by all clients.
So here iam explaining how to extract data from an excel sheet simply using php.
If you need to do large data migration from an excel sheet to your MySQL database, the most conventional way is to convert the .xls or .xlsx files to simple CSV(comma seperated file) and read it using PHP file read function. However we can also read a .xls file without converting it to a csv file. We can even navigate through the various worksheets in a single file.

You can get source library from this link Dowload here

I will explain it with an example...

Iam converting the below excel sheet to php format :-


First we need to include the main class file in our PHP page and initialise an object for it as follows:

include 'reader.php';
$excel = new Spreadsheet_Excel_Reader();

Now we are loading the excel file using the above created object as:
$excel->read('sample.xls');

Now we navigate through the rows and columns of the first worksheet in the excel file and display it as a simple HTML table in the browser:

$x=1;
    while($x<=$excel->sheets[0]['numRows']) {
      echo "\t<tr>\n";
      $y=1;
      while($y<=$excel->sheets[0]['numCols']) {
        $cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
        echo "\t\t<td>$cell</td>\n"; 
        $y++;
      } 
      echo "\t</tr>\n";
      $x++;
    }

In the above sheet[0] is used to read cells from the first work sheet, you can change it according to your needs. Now in sheets[0]['cells'], ['cells'] is a 2D array storing the data as shown in the above screen shot. After executing the entire source code, this is the output that is generated:

so code will be:-

1) download library file from the source i provided earlier..
2)the sample file would be like this:-

<html>
  <head>
    <style type="text/css">
    table {
    border-collapse: collapse;
    }        
    td {
    border: 1px solid black;
    padding: 0 0.5em;
    }        
    </style>
  </head>
  <body>
<?php
include 'reader.php';
    $excel = new Spreadsheet_Excel_Reader();
?>
Sheet 1:<br/><br/>
    <table>
    <?php
    $excel->read('record.xls');  
    $x=1;
    while($x<=$excel->sheets[0]['numRows']) {
      echo "\t<tr>\n";
      $y=1;
      while($y<=$excel->sheets[0]['numCols']) {
        $cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
        echo "\t\t<td>$cell</td>\n";  
        $y++;
      }  
      echo "\t</tr>\n";
      $x++;
    }
    ?>    
    </table><br/>

    ?>    
    </table>


  </body>
</html>

Resolving "headers already send" warning in PHP

When I was learning PHP their were few things that had stumped me, I would usually take it hours to solve them if not days.
Today I am going to write about one such annoying problem that almost always comes in the way of PHP developers at least once.

Warning: Cannot modify header information – headers already sent by (output started at C:wampwwwaktesterror.php:2) in C:wampwwwaktesterror.php on line 4

Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:wampwwwaktesterror.php:2) in C:wampwwwaktesterror.php on line 3

This is “header already sent” warning message, that we get whenever we try to redirect a user to some other page or location, when we try to set a cookie or if we try to start a session. Once we get this warning we know that page won’t redirect, session won’t start or cookie’s sent to user, So we can’t even ignore them.

Before we see the solutions to resolve this warning let’s see the source code of the error.php file that I used to generate this error.


<?php

session_start();
header("location:file.php");
?>

Please notice an empty line before “<?php”, this is the cause of errors in his page.


Why This Occurs??

This is requirement of the http protocol that header related information must be sent by the server before it can sent the content. When we try to send a header information after we have already sent some output to client, PHP responds by giving this warning.

The most common reasons are :-


  • An output is sent, either by normal HTML tags, blank lines in a file, or from PHP file itself(in my case this is the reason).
  • We read a file using include()/require() function, and that file may have empty spaces or he lines at the end, that will be sent as output.
  • Important thing to note is that output is sent before header information that you wanted to sent, and hence the warning.


How To Resolve??

This is really simple, just make sure their is no output sent before your call to header function. This might be a correct advice but this still does not help much.

What really needed is that we need to know where is the exact problem, that we can resolve.

Basically we have to make sure that no output is sent before call to any header related functions.

Some guideline that might help


  • Always start “<?php” at the first line and first column, in you php file.
  • Keep all you your session related function like session_start() at the start of file, just after “<?php”
  • If all you are writing is a php file then do not use “?>”, this can prevent empty space or lines from being included in the other files.
  •  use ob_start(); at begining of php file. This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.


If you have any doubts or you did not understand something leave a comment below, I will try to help you as time permits.