Showing posts with label Core PHP. Show all posts
Showing posts with label Core PHP. Show all posts

Friday, 31 March 2017

Sample Code For Deleting Parent and Child N level


Sample Code For Deleting Parent and Child N level

 private function deleteChildren($parentId) {
      $lochid = new Location();
      $children = $lochid->where("parent_id", $parentId)->get();
      if (!empty($children)) {
            foreach ($children as $child) {
                $this->deleteChildren($child->id);
                $this->db->delete('countries_locations', array('id' =>$child->id)); 
            }
        }
    }

Image upoad with dir creation in YII

if(!is_dir(Yii::getPathOfAlias('webroot').'/'.$imagepath))
{
          if(!defined('FS_CHMOD_DIR')){
            define('FS_CHMOD_DIR', 0755);
           }
        mkdir(Yii::getPathOfAlias('webroot').'/'.$imagepath);
}

$OriImage = Yii::getPathOfAlias('webroot').'/'.$model->{$field}; 
$stat = stat(dirname($OriImage));
$perms = $stat['mode'] & 0000666;
$logo->saveAs($OriImage);
@chmod($OriImage,$perms);

Friday, 24 June 2016

SHOW PHP UTC DATE TIME TO USER SPECIFIC LOCAL TIME

function userspecifictime($added_date, $id, $return=true) {
        $p_added_date= $added_date;    
        $scripttag = '<script type="text/javascript">                    
            var dateSR = new Date();
            var offsetms = dateSR.getTimezoneOffset() * 60 * 1000;
            var serverDate = new Date("'.$p_added_date.'");
            serverDate = new Date(serverDate.valueOf() - offsetms);    
            var hrs = serverDate.getHours();
            var mi = serverDate.getMinutes();
            var merd = "am";
            if(hrs >= 12) {
                if(hrs > 12) {
                    hrs = hrs - 12;
                }
                merd = "pm";
            }
            hrs = (hrs < 10) ? "0"+hrs : hrs;
            mi = (mi < 10) ? "0"+mi : mi;
            ft=hrs+":"+mi+" "+merd;
            document.getElementById("'.$id.'").innerHTML = ft;
        </script>';
        if($return) {
            return $scripttag;
        } else {
            echo $scripttag;
        }
    }

<?php
<p id="timeid"></p>
$dateInUTC_Format = '2016-06-24 11:43:30';
userspecifictime($dateInUTC_Format,'timeid',false);
?>

Sunday, 15 November 2015

Steps To Add Google Translate Widget (Multi-lingual) (PHP WEB SITE)

1. Login in to your Gmail account.
2. Than click on open the following link "https://translate.google.com/manager/website/add";
3. Add your domain url to following "Website URL" => "What is the URL of your website?" input box.
4. Select the Google Translate widget (Plugin Settings) for your website.
5. Click the "Get Code" button.
6. Copy the generated js code (Paste this code onto your website) and place in your header file where you want to display this widget on web site.
7. save your file.

8. Refresh your page.. if you have followed all the above steps correctly than you are able to see the google translate widget.

Thanks Cheers... :)

Thursday, 7 August 2014

How to get the day name from the date in php

If you solution for getting a day name from any past of future day, You are at right page of web.
Use below code.

<?php
$date  = '12-Jul-2014'; // Use any valid PHP date format
$timestamp = strtotime($date);
echo 'Short Name of Day => '. $day = date('D', $timestamp); //Short Name of Day => Sat
echo '<br> Full Name of Day => '. $day = date('l', $timestamp); //Full Name of Day => Saturday
?>


Tuesday, 5 August 2014

How to Resize Image Dynamically in PHP

How to Resize Image Dynamically in PHP

There is an extremely useful PHP library called timthumb which comes very handy. It’s just a simple PHP script that you need to download and put in some folder under your website. And then simply call it with appropriate arguments.






  • Download timthumb.php and put under any folder.
  • Upload this script timthumb.php though FTP to your web hosting. Put it under a directory /script.
  • Just call timthumb.php with appropriate arguments, For example:
    <img src="/script/timthumb.php?src=/some/path/myimage.png&w=100&h=80"
        alt="resized image" />

    And that’s all!!


  • One thing worth noting here is that this library will create a folder cache in the directory where timthumb.php script resides. This folder will cache the resized image for better performance.

    You can refer following table for different parameters and its meaning.

    ParameterValuesMeaning
    srcsourceurl to imageTells TimThumb which image to resize
    wwidththe width to resize toRemove the width to scale proportionally (will then need the height)
    hheightthe height to resize toRemove the height to scale proportionally (will then need the width)
    qquality0 – 100Compression quality. The higher the number the nicer the image will look. I wouldn’t recommend going any higher than about 95 else the image will get too large
    aalignmentc, t, l, r, b, tl, tr, bl, brCrop alignment. c = center, t = top, b = bottom, r = right, l = left. The positions can be joined to create diagonal positions
    zczoom / crop0, 1, 2, 3Change the cropping and scaling settings
    ffilterstoo many to mentionLet’s you apply image filters to change the resized picture. For instance you can change brightness/ contrast or even blur the image
    ssharpenApply a sharpen filter to the image, makes scaled down images look a little crisper
    cccanvas colourhexadecimal colour value (#ffffff)Change background colour. Most used when changing the zoom and crop settings, which in turn can add borders to the image.
    ctcanvas transparencytrue (1)Use transparency and ignore background colour



    Hope this is useful for you :)

    Friday, 18 July 2014

    How to calculate the weeks between two dates

    How to calculate the weeks between two dates.

    //php code
    $today=date('Y-m-d h:i:s');
    $fromData="2014-01-01 00:00:00"
    $diff = strtotime($today, 0) - strtotime($fromData, 0);
    $weekNo = floor($diff / 604800);
    $weekNo = $weekNo+1;
    echo "This is the ".$weekNo." of the Year 2014";
    //end

    Wednesday, 16 April 2014

    PHP: How to Copy All Files and folders Within A Directory

    function recurse_copy($src,$dst) {
            $dir = opendir($src);
            @mkdir($dst, 0777);
            while(false !== ( $file = readdir($dir)) ) {
                    if (( $file != '.' ) && ( $file != '..' )) {
                            if ( is_dir($src . '/' . $file) ) {
                                    $this->recurse_copy($src . '/' . $file,$dst . '/' . $file);
                            }
                            else {
                                    copy($src . '/' . $file,$dst . '/' . $file);
                            }
                    }
            }
            closedir($dir);
        }

    Example : How to use above Function

    $src='www/abc'; // copy all the files and folder within abc directory
    $dst = 'www/newdir' //
    recurse_copy($src,$dst);

    above function first create the destination directory and than copy all the source directory content.
    Tips: to create directory and set its permission using following code in php
    mkdir($path, 0777, true)

    PHP: Unlink All Files Within A Directory, and then Deleting That Directory

    function recursiveRemoveDirectory($directory)
        {
            foreach(glob("{$directory}/*") as $file)
            {
                    if(is_dir($file)) {
                            $this->recursiveRemoveDirectory($file);
                    } else {
                            unlink($file);
                    }
            }
            rmdir($directory);
        }

    Example : How to use above function.
    $directory = 'www/abc';
    recursiveRemoveDirectory($directory)

    Friday, 28 March 2014

    Get Domain name from the URL using php function

    function get_domain($url)
    {
      $pieces = parse_url($url);
      $domain = isset($pieces['host']) ? $pieces['host'] : '';
      if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
        return $regs['domain'];
      }
      return false;
    }

    print get_domain("http://www.sanajyrao.com"); // outputs 'sanajyrao.com'
    print get_domain("http://www.demo.sanajyrao.com"); // outputs 'sanajyrao.com'
    print get_domain("http://demo.sanajyrao.com"); // outputs 'sanajyrao.com'
    print get_domain("http://sanajyrao.com"); // outputs 'sanajyrao.com'

    Sort Array values using specific(particuler) Key of array

    function sort_arr_of_obj($array, $sortby, $direction='asc') {
       
        $sortedArr = array();
        $tmp_Array = array();
       
        foreach($array as $k => $v) {
            $tmp_Array[] = strtolower($v[$sortby]);
        }
       
        if($direction=='asc'){
            asort($tmp_Array);
        }else{
            arsort($tmp_Array);
        }
       
        foreach($tmp_Array as $k=>$tmp){
            $sortedArr[] = $array[$k];
        }
       
        return $sortedArr;

    }

    $myArray=array(0=>array('size'=>5,'name'=>'Five'),1=>array('size'=>3,'name'=>'Three'),2=>array('size'=>9,'name'=>'Nine'));
    $myArray=sort_arr_of_obj($myArray,'size','asc');


    Friday, 15 November 2013

    Get Visitor Info Using Their IP Address

    funtion getVisitorInfo($userip,$output){
            $result  = "Unknown";     
            $url =  "http://www.geoplugin.net/json.gp?ip=".$ip;
            $data = file_get_contents($url);  
            $ip_data = @json_decode($data);
            if($ip_data && $ip_data->$output != null)
            {
               $result = $ip_data->$output;
            }
            return $result;
    }
    $userip = $_SERVER['REMOTE_ADDR'];
    //Get Country Name
    $userCountryName = getVisitorInfo($userip,'geoplugin_countryName');
     //Get Country Code
    $userCountryCode = getVisitorInfo($userip,'geoplugin_countryCode'); 


    Below is list of infromation can be get from user ip.
    geoplugin_request,
    geoplugin_status,
    geoplugin_credit,
    geoplugin_city,
    geoplugin_region,
    geoplugin_areaCode,
    geoplugin_dmaCode,
    geoplugin_countryCode,
    geoplugin_countryName,
    geoplugin_continentCode,
    geoplugin_latitude,
    geoplugin_longitude,
    geoplugin_regionCode,
    geoplugin_regionName,
    geoplugin_currencyCode,
    geoplugin_currencySymbol,
    geoplugin_currencySymbol_UTF8,
    geoplugin_currencyConverter

    Note:You need to allow allow_url_fopen in your php.ini config file.

    Friday, 31 May 2013

    "Get list of images based on width and height AND get list of files from a directory based on files extenstion"

    <?php
    /* "get list of images based on width and height" */
    $dirpath = 'imgdirname'; // Name of folder(directory) containing the images files
    function getimg($w,$h,$dirpath)
    {
        $filesimg= array();
        $dh  = opendir($dirpath);
        while (false !== ($filename = readdir($dh)))
        {
            if(!is_dir($filename))
            {
                $imginfo = getimagesize($dirpath.'/'.$filename);
                if($imginfo[0] == $w || $imginfo[0] == $h ){
                    $filesimg[] = $filename;
                }
            }
        }
        sort($filesimg);
        return $filesimg;
    }
    $imgdata = getimg(100,100,$dirpath);
    echo "<pre>";print_r($imgdata); exit;

    /* get list of html files from a directory*/
    $dirpath = 'htmlfiledirc'; // Name of folder(directory) containing all the html files
    function getHtmlfileList($dirpath,$fileExt)
    {
        $fileshtml= array();
        $dh  = opendir($dirpath);
        while (false !== ($filename = readdir($dh)))
        {
            $files[] = $filename;
            if(!is_dir($filename) && strstr($filename,$fileExt)){
                $fileshtml[] = $filename;
            }
        }
        return $fileshtml;
    }
    $fileExt = '.html';
    $filesdata = getHtmlfileList($dirpath,$fileExt);
    echo "<pre>";print_r($imgdata); exit;
    ?>

    Monday, 13 May 2013

    "PHP Function For Truncate string and function For Truncate string"

    /* Below function  For Truncate string */
        function truncate($text, $chars) {
        $add_dots='';
        if(strlen($text) > $chars){
            $add_dots = "...";
        }
        $text = str_replace('"','&rdquo;',$text);
        $text = str_replace('"','&ldquo;',$text);
        $text = str_replace("\n", "", $text);
        $text = str_replace("\r", "", $text);


        $text = $text." ";
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text = $text.$add_dots;
        return $text;
        }
        /*Function for refine tag and quotes in description. */
        function refineTagQuotes($text)
        {
            $text = str_replace('"','&rdquo;',$text);
            $text = str_replace('"','&ldquo;',$text);
            $text = str_replace("\n", "", $text);
            $text = str_replace("\r", "", $text);
            return $text;
        }

    Wednesday, 8 May 2013

    Image Upload With Resize



    Image Upload With Resize

    Create following directory structure
    ImageResize (foldername)
    ImageUploadWithResize.php
    delete_all_images.php
    uploads (foldername add 777 permission to this folder)

    ImageUploadWithResize.php

    <?php
    //Define Memory Limit for large images so that we do not get "Allowed memory exhausted"
    ini_set("memory_limit", "200000000");


    // upload the file
    if ((isset($_POST["submitted_form"])) && ($_POST["submitted_form"] == "image_upload_form")) {
                // file needs to be jpg,gif,bmp,x-png and 4 MB max
                if (($_FILES["image_upload_box"]["type"] == "image/jpeg" || $_FILES["image_upload_box"]["type"] == "image/pjpeg" || $_FILES["image_upload_box"]["type"] == "image/gif" || $_FILES["image_upload_box"]["type"] == "image/x-png") && ($_FILES["image_upload_box"]["size"] < 4000000))
                {
                            // some settings
                            $max_upload_width = 2592; $max_upload_height = 1944;
                            // if user chosed properly then scale down the image according to user preferances
                            if(isset($_REQUEST['max_width_box']) and $_REQUEST['max_width_box']!='' and $_REQUEST['max_width_box']<=$max_upload_width){
                                        $max_upload_width = $_REQUEST['max_width_box'];
                            }   
                            if(isset($_REQUEST['max_height_box']) and $_REQUEST['max_height_box']!='' and $_REQUEST['max_height_box']<=$max_upload_height){
                                        $max_upload_height = $_REQUEST['max_height_box'];
                            }         

                            // if uploaded image was JPG/JPEG
                if($_FILES["image_upload_box"]["type"] == "image/jpeg" || $_FILES["image_upload_box"]["type"] == "image/pjpeg")
    {         
                                        $image_source = imagecreatefromjpeg($_FILES["image_upload_box"]["tmp_name"]);
                            }                     
                            // if uploaded image was GIF
                            if($_FILES["image_upload_box"]["type"] == "image/gif"){
                                        $image_source = imagecreatefromgif($_FILES["image_upload_box"]["tmp_name"]);
                            }         
                            // BMP doesn't seem to be supported so remove it form above image type test (reject bmps)           
                            // if uploaded image was BMP
                            if($_FILES["image_upload_box"]["type"] == "image/bmp"){          
                                        $image_source = imagecreatefromwbmp($_FILES["image_upload_box"]["tmp_name"]);
                            }                                 
                            // if uploaded image was PNG
                            if($_FILES["image_upload_box"]["type"] == "image/x-png"){
                                        $image_source = imagecreatefrompng($_FILES["image_upload_box"]["tmp_name"]);
                            }
                           
                           
                            $remote_file = "uploads/".$_FILES["image_upload_box"]["name"];
                            imagejpeg($image_source,$remote_file,100);
                            chmod($remote_file,0644);
                           
                            // get width and height of original image
                            list($image_width, $image_height) = getimagesize($remote_file);
               
                            if($image_width>$max_upload_width || $image_height >$max_upload_height){
                                        $proportions = $image_width/$image_height;
                                       
                                        if($image_width>$image_height){
                                                    $new_width = $max_upload_width;
                                                    $new_height = round($max_upload_width/$proportions);
                                        }                     
                                        else{
                                                    $new_height = $max_upload_height;
                                                    $new_width = round($max_upload_height*$proportions);
                                        }                     
                                       
                                       
                                        $new_image = imagecreatetruecolor($new_width , $new_height);
                                        $image_source = imagecreatefromjpeg($remote_file);
                                       
                                        imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
                                        imagejpeg($new_image,$remote_file,100);
                                       
                                        imagedestroy($new_image);
                            }
                           
                            imagedestroy($image_source);
                           
                           
                            header("Location: ImageUploadWithResize.php?upload_message=image uploaded&upload_message_type=success&show_image=".$_FILES["image_upload_box"]["name"]);
                            exit;
                }
                else{
                            header("Location: ImageUploadWithResize.php?upload_message=make sure the file is jpg, gif or png and that is smaller than 4MB&upload_message_type=error");
                            exit;
                }
    }
    ?>

    <html>
    <head><title>Image Upload with resize</title>
    <style type="text/css">
    <!--
    .upload_message_success {padding:4px;background-color:#009900;border:1px solid #006600;color:#FFFFFF;margin-top:10px;margin-bottom:10px;}
    .upload_message_error {padding:4px;background-color:#CE0000;border:1px solid #990000;color:#FFFFFF;margin-top:10px;margin-bottom:10px;}
    -->
    </style></head>
    <body>
    <h1 style="margin-bottom: 0px">Upload an image</h1>
    <?php if(isset($_REQUEST['upload_message'])){?>
                <div class="upload_message_<?php echo $_REQUEST['upload_message_type'];?>">
                            <?php echo htmlentities($_REQUEST['upload_message']);?>
                </div>
    <?php }?>
    <form action="#" method="post" enctype="multipart/form-data" name="image_upload_form" id="image_upload_form" style="margin-bottom:0px;">
                <label>Image file, maximum 4MB. it can be jpg, gif,  png:</label><br />
        <input name="image_upload_box" type="file" id="image_upload_box" size="40" />
        <input type="submit" name="submit" value="Upload image" /><br /><br />
                <label>Scale down image? (2592 x 1944 px max):</label><br />
                <input name="max_width_box" type="text" id="max_width_box" value="1024" size="4"> x
                <input name="max_height_box" type="text" id="max_height_box" value="768" size="4"> px.
        <br /><br />
                <p style="padding:5px; border:1px solid #EBEBEB; background-color:#FAFAFA;">
                            <strong>Notes:</strong><br />
                            The image will not be resized to this exact size; it will be scalled down so that neider width or height is larger than specified.<br />
                            After you uploaded images and made tests on our server please <a href="delete_all_images.php">delete all uploaded images </a> :)<br />
                </p>
                <input name="submitted_form" type="hidden" id="submitted_form" value="image_upload_form" />
    </form>
    <?php if(isset($_REQUEST['show_image']) and $_REQUEST['show_image']!=''){?>
    <p><img src="uploads/<?php echo $_REQUEST['show_image'];?>" /></p>
    <?php }?>
    </body>
    </html>

    delete_all_images.php

                <!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>Delete all images</title>
    </head>

    <body>

    <?
       $dir = 'uploads/';
       // open specified directory
       $dirHandle = opendir($dir);
       $total_deleted_images = 0;
       while ($file = readdir($dirHandle)) {
          // if not a subdirectory and if filename contains the string '.jpg'
          if(!is_dir($file)) {
             // update count and string of files to be returned
                             unlink($dir.$file);
             echo 'Deleted file <b>'.$file.'</b><br />';
                             $total_deleted_images++;
          }
       }
       closedir($dirHandle);
                if($total_deleted_images=='0'){
                            echo 'There ware no files uploaded there.';
                }
                echo '<br />Thank you.';
                echo '<br /><a href="ImageUploadWithResize.php" title="Upload Image"> Upload New Image </a>';

    ?>

    </body>
    </html>

    Monday, 6 May 2013

    PHP Time Stamp Function

    time_stamp.php
    Contains PHP code. You have to use the time_stamp() function to display the date and time.

    <?php
    function time_stamp($session_time)
    {
    $time_difference = time() - $session_time ;

    $seconds = $time_difference ;
    $minutes = round($time_difference / 60 );
    $hours = round($time_difference / 3600 );
    $days = round($time_difference / 86400 );
    $weeks = round($time_difference / 604800 );
    $months = round($time_difference / 2419200 );
    $years = round($time_difference / 29030400 );



    // Seconds
    if($seconds <= 60)
    {
    echo "$seconds seconds ago";
    }
    //Minutes
    else if($minutes <=60)
    {

       if($minutes==1)
      {
       echo "one minute ago";
       }
       else
       {
        echo "$minutes minutes ago";
       }

    }
    //Hours
    else if($hours <=24)
    {

       if($hours==1)
      {
       echo "one hour ago";
      }
      else
      {
       echo "$hours hours ago";
      }

    }
    //Days
    else if($days <= 7)
    {

      if($days==1)
      {
       echo "one day ago";
      }
      else
      {
       echo "$days days ago";
       }

    }
    //Weeks
    else if($weeks <= 4)
    {

       if($weeks==1)
      {
       echo "one week ago";
       }
      else
      {
       echo "$weeks weeks ago";
      }

    }
    //Months
    else if($months <=12)
    {

       if($months==1)
      {
       echo "one month ago";
       }
      else
      {
       echo "$months months ago";
       }

    }
    //Years
    else
    {

       if($years==1)
       {
        echo "one year ago";
       }
       else
      {
        echo "$years years ago";
       }

    }

    }
    $session_time ="1264326122";
    //$session_time=time();
    echo time_stamp($session_time);
    ?>

    Friday, 26 April 2013

    Function for create parent child Tree FROM Array

    <?php
    /* Function for create parent child Tree*/
    function buildTree(array $elements, $parentId = '')
    {
            $branch = array();
            foreach ($elements as $element)
        {
                if ($element['parent'] == $parentId)
            {
                $children = buildTree($elements, $element['id']);
                if ($children) {
                $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }   

    $mainarray = array(
    "0"=>array("id"=>1,"orderby"=>"10","title"=>"Home","link"=>"home.php","active"=>"Y","parent"=>""),
    "1"=>array("id"=>2,"orderby"=>"20","title"=>"Item1","link"=>"item.php","active"=>"Y","parent"=>""),
    "2"=>array("id"=>3,"orderby"=>"30","title"=>"Item2","link"=>"item2.php","active"=>"Y","parent"=>""),
    "3"=>array("id"=>14,"orderby"=>"80","title"=>"Item3","link"=>"item3.php","active"=>"Y","parent"=>""),
    "4"=>array("id"=>4,"orderby"=>"40","title"=>"Sub1Item1","link"=>"sub1item.php","active"=>"Y","parent"=>"2"),
    "5"=>array("id"=>5,"orderby"=>"50","title"=>"Sub2Item1","link"=>"sub2item.php","active"=>"Y","parent"=>"2"),
    "6"=>array("id"=>6,"orderby"=>"60","title"=>"Sub3Item1","link"=>"sub3item.php","active"=>"Y","parent"=>"2"),
    "7"=>array("id"=>10,"orderby"=>"70","title"=>"Sub2Sub1Item1","link"=>"sub1item1.php","active"=>"Y","parent"=>"4"),
    );
    $mainarray = buildTree($mainarray);
    echo "<pre>";print_r($mainarray); exit;
    ?>

    Thursday, 25 April 2013

    Create dynamic tab menu based on display alphabatic range

     /* Create dynamic tab menu based on display alphabatic range Save below code as dynamictabmanu.php and put it along with images*/

     <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
     <script type="text/javascript">
            $(document).ready(function()
            {        
                 $("ul#brandstab li:first").addClass("activebox");
                 $("div#divcontentbox div:first").css("display","block");
                  $('ul#brandstab li a').click(function()
                {           
                          $("ul#brandstab li").removeClass("activebox");
                          $(this).parent().addClass("activebox");
                    $(".abi_htab_content").css("display","none");
                     var divid =   $(this).attr("rel");
                    $(divid).css("display","block");
                  });         
            });
            </script>
            <style type="text/css">
            #divcontentbox .abi_htab_content{display:none;}       
            #brandstab{height: 46px; margin: 0; padding: 0;}
            #brandstab li.activebox, #brandstab li:hover  {background: none repeat scroll 0 0 #F0F0F0;  bottom: -1px;    position: relative;}
            #brandstab li{border-radius: 6px 6px 0 0;  cursor: pointer;  float: left; list-style: none outside none;  margin-right: 1px;  padding: 0 10px;}
            #brandstab li a{color: #CCCCCC;   display: block;    line-height: 9px;    text-decoration: none;}
            #brandstab li.activebox a h3, #brandstab li a h3:hover {color:#000;}
            #divcontentbox { background: none repeat scroll 0 0 #F0F0F0;padding: 10px;}
            div.datablock{float:left; margin:15px;}
            </style>
    <?php
    $display_range = 'A-H,I-Z'; // change this as per need for example create three tab set range like this 'A-H,I-P,Q-Z'
    $resexplode = explode(',',$display_range);
    $mainarray = array(
                            "0"=>array("id"=>1,"title"=>"AR","img"=>"ar.jpg","w"=>100,"h"=>100),
                            "1"=>array("id"=>10,"title"=>"CR","img"=>"cr.jpg","w"=>100,"h"=>100),
                            "2"=>array("id"=>20,"title"=>"HR","img"=>"hr.jpg","w"=>100,"h"=>100),
                            "3"=>array("id"=>25,"title"=>"HK","img"=>"hk.jpg","w"=>100,"h"=>100),
                            "4"=>array("id"=>30,"title"=>"KP","img"=>"kp.jpg","w"=>100,"h"=>100),
                            "5"=>array("id"=>40,"title"=>"SR","img"=>"sr.jpg","w"=>100,"h"=>100),
                            "6"=>array("id"=>50,"title"=>"SK","img"=>"sk.jpg","w"=>100,"h"=>100),
                            "7"=>array("id"=>55,"title"=>"VJ","img"=>"vj.jpg","w"=>100,"h"=>100),
                            "8"=>array("id"=>58,"title"=>"ZQ","img"=>"zq.jpg","w"=>100,"h"=>100),
                      );
                     
            $recAH =  array();
          $brandcollection =  array();
          $data = array();     
          for($k=0;$k<count($resexplode);$k++)
          { 
              $charsetLetter  =  explode('-',$resexplode[$k]);
              if(count($charsetLetter) == 2)
              {
                  $datastr =  $charsetLetter[0]."2".$charsetLetter[1];
                  $recAH = range($charsetLetter[0], $charsetLetter[1]);
                  for($i=0;$i<count($mainarray);$i++)
                  { 
                        $brandname = trim($mainarray[$i]['title']);
                        $char = ucfirst(substr($brandname, 0,1));
                        if(in_array($char,$recAH)){
                          $mainarray[$i]['class'] = $charsetLetter[0]."2".$charsetLetter[1];
                          $data[] =   $mainarray[$i];          
                        }
                  }
                  array_filter($data);        
                  $brandcollection[$k]= $data;
                  unset($data); 
              }
          }  
              echo '<ul class="abi_htabs" id="brandstab">';
             for($k=0;$k<count($resexplode);$k++){ echo '<li><a rel="#'.$resexplode[$k].'"><h3>'.$resexplode[$k].'</h3></a></li>';}
              echo '</ul>';
             echo '<div class="abi_htab_container" id="divcontentbox">';
             for($k=0;$k<count($resexplode);$k++)
            {
                echo '<div id="'.$resexplode[$k].'" class="abi_htab_content">';
                for($i=0;$i<count($brandcollection[$k]);$i++)
                {
                    echo '<div class="datablock"><div class="title">'.$brandcollection[$k][$i]['title'].'</div>';
                    echo '<div class="img"><img src="'.$brandcollection[$k][$i]['img'].'" width="'.$brandcollection[$k][$i]['w'].'" height="'.$brandcollection[$k][$i]['h'].'"></div>';
                    echo '</div>';   
                }
                echo '<br style="clear:both;">';
                echo '</div>';
            }
             echo '</div>';
    ?>

    Dispaly Image in Ratio

    <?php
    /*save below code as demo.php. */
    /* Dispaly Image in ratio */
    $inputwidth=$_GET['w']; //new user define width for image
    $inputheight=$_GET['h']; //new user define Height for image
    $imgsrc=$_GET['src']; // imagepath from where image need to be load.
    //get image details
    list($width, $height, $type, $attr) = getimagesize($imgsrc);
    //Generate new height and width based on original image size in ratio
    if (($width/$height) > ($inputwidth/$inputheight))
    {
        $outputwidth = $inputwidth;
        $outputheight = ($inputwidth * $height)/ $width;
    }// And if the image is taller rather than wider, then set the height and figure out the width
    elseif (($width/$height) < ($inputwidth/$inputheight)) {
                    $outputwidth = ($inputheight * $width)/ $height;
                      $outputheight = $inputheight;
    }    // And because it is entirely possible that the image could be the exact same size/aspect ratio of the desired area,
    elseif (($width/$height) == ($inputwidth/$inputheight))
    {
        $outputwidth = $inputwidth;
        $outputheight = $inputheight;
    }             
    echo '<img src="'.$imgsrc.'" width="'.$outputwidth.'" height="" alt="'.$outputheight.'">';
    ?>

    Wednesday, 24 April 2013

    Function for DELETE ALL CHILDREN OF A PARENT CATEGORIES
    function deleteChildren($parentId) {
          $lochid = new Location();
          $children = $lochid->where("parent_id", $parentId)->get();
          if (!empty($children)) {
                foreach ($children as $child) {
                    $this->deleteChildren($child->id);
                    $this->db->delete('countries_locations', array('id' =>$child->id));
                }
            }
        }


    Function for update ALL CHILDREN VALUE WHEN PARENT IS UPDATED OF A PARENT CATEGORIES
    function updateChildren($parentId) {

          $sql = "SELECT * from  xcart_categories WHERE parentid='$parentId'";
          $children = func_query($sql);
          if (!empty($children)) {
                foreach ($children as $key=>$val) {
                    $childcatid = $val['categoryid'];
                    $child_data = array('to_show_top_nav' =>'Y');
                    func_array2update('categories', $child_data, "categoryid='".intval($childcatid)."'");
                    updateChildren($childcatid);
               }
            }
        }


    /* Function for create parent and child from an array */
    $speed_bar = array();
    $speed_bar = buildTree($speed_bar);
    function buildTree(array $elements, $parentId = '')
    {
            $branch = array();
            foreach ($elements as $element)
        {
                if ($element['parent'] == $parentId)
            {
                $children = buildTree($elements, $element['id']);
                if ($children) {
                $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }    


    /* Code FOR GET Number of days between TWO TIME STAMP


    $lastapplytime=$lastdatetimestemp;
    $todaytime = time();
    $diff = abs($todaytime - $lastapplytime);
    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
    $diff2 =  $days+($months*30);

    OR

    $numDays = floor(abs($lastapplytime - $todaytime)/60/60/24);

    List OF BANK PAN Numbers

    List OF BANK PAN Numbers Bank/Home Loan Providers PAN Number Allahabad Bank AACCA8464F Andhra Bank AABCA7375C Axis Bank...