Tuesday, December 18, 2012

php image upload class file

<?php

    class Uploader
    {
        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   =   $_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($_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 deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }

    }

?>
Now upload files using Uploader class. Use following code . Code block is self explanatory .

<?php

$uploader   =   new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
$uploader->setMaxSize(.5);                          //set max file size to be allowed in MB//

if($uploader->uploadFile('txtFile')){   //txtFile is the filebrowse element name //   
    $image  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

}else{//upload failed
    $uploader->getMessage(); //get upload error message
}


?>

Thursday, December 13, 2012

array pagination using php class

<?php


  class pagination
  {
    var $page = 1; // Current Page
    var $perPage = 10; // Items on each page, defaulted to 10
    var $showFirstAndLast = false; // if you would like the first and last page options.
   
    function generate($array, $perPage = 10)
    {
      // Assign the items per page variable
      if (!empty($perPage))
        $this->perPage = $perPage;
     
      // Assign the page variable
      if (!empty($_GET['page'])) {
        $this->page = $_GET['page']; // using the get method
      } else {
        $this->page = 1; // if we don't have a page number then assume we are on the first page
      }
     
      // Take the length of the array
      $this->length = count($array);
     
      // Get the number of pages
      $this->pages = ceil($this->length / $this->perPage);
     
      // Calculate the starting point
      $this->start  = ceil(($this->page - 1) * $this->perPage);
     
      // Return the part of the array we have requested
      return array_slice($array, $this->start, $this->perPage);
    }
    function getpage($total)
    {
        $perPage=$this->perPage;
        $sratpage=$this->start;
        if($perPage>$total)
         {
                  echo "Results ".($sratpage+1)."-"; echo $total; echo " of ".$total;
         }else{
               
                if($sratpage==0)
                {
                        echo "Results ".($sratpage+1)."-"; echo $perPage; echo " of ".$total;
                }else{
                        $endpage=($sratpage+$perPage);
                        if($endpage>$total)
                        {
                         echo "Results ".$sratpage."-"; echo $total;echo " of ".$total;
                        }
                        else
                        {
               
                        echo "Results ".$sratpage."-"; echo $endpage;echo " of ".$total;
                        }
                           
               
                }
    }
   
  }
    function links()
    {
      // Initiate the links array
      $plinks = array();
      $links = array();
      $slinks = array();
     
      // Concatenate the get variables to add to the page numbering string
      if (count($_GET)) {
        $queryURL = '';
        foreach ($_GET as $key => $value) {
          if ($key != 'page') {
           // $queryURL .= '&'.$key.'='.$value;
          }
        }
      }
     
      // If we have more then one pages
      if (($this->pages) > 1)
      {
        // Assign the 'previous page' link into the array if we are not on the first page
        if ($this->page != 1) {
          if ($this->showFirstAndLast) {
            $plinks[] = ' <a href="?page=1'.$queryURL.'">&laquo;&laquo; First </a> ';
          }
          $plinks[] = ' <span class="paginationPrev"><a href="?page='.($this->page - 1).$queryURL.'">&laquo; Prev</a></span> ';
        }
       
        // Assign all the page numbers & links to the array
        echo '<span nowrap="nowrap" align="center">';
        for ($j = 1; $j < ($this->pages + 1); $j++) {
          if ($this->page == $j) {
            $links[] = ' <span class="selected1">'.$j.'</span> '; // If we are on the same page as the current item
          } else {
            $links[] = ' <a href="?page='.$j.$queryURL.'">'.$j.'</a>'; // add the link to the array
          }
        }
        echo '</span>';
        echo '<span class="paginationNext">';
        // Assign the 'next page' if we are not on the last page
        if ($this->page < $this->pages) {
          $slinks[] = ' <a href="?page='.($this->page + 1).$queryURL.'"> Next &raquo; </a> ';
          if ($this->showFirstAndLast) {
            $slinks[] = ' <a href="?page='.($this->pages).$queryURL.'"> Last &raquo;&raquo; </a> ';
          }
        }
        echo '</span>';
        // Push the array into a string using any some glue
        return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
      }
      return;
    }
  }
?>