PHP

                                                                                    << BACK

Setup with Mysql DB connection :  DOWNLOAD

Setup with Mysql DB connection - Jquery :  DOWNLOAD

Sortable in PHP + Jquery :  DOWNLOAD
---------------------------------------------------------------------------------------------
Function :
Explode :
<?PHP
  $pizza  = "piece1,piece2,piece3,piece4,piece5,piece6";
  $pieces = explode(",", $pizza);
  echo $pieces[0]; // piece1
  echo $pieces[1]; // piece2

//The explode() function breaks a string into an array.
//Note: The "separator" parameter cannot be an empty string.
//Note: This function is binary-safe.
?>

Substr:
<?PHP
  $rest = substr("abcdef", 0, -1);  // returns "abcde"
  $rest = substr("abcdef", 2, -1);  // returns "cde"
  $rest = substr("abcdef", 4, -4);  // returns false
  $rest = substr("abcdef", -3, -1); // returns "de"

//The substr() function returns a part of a string.
//Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.
?>

Array Reverse:
<?PHP
  $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
  print_r(array_reverse($a));

  Output:  Array ( [c] => Toyota [b] => BMW [a] => Volvo )
 //The array_reverse() function returns an array in the reverse order.
?>

Array Unique:
<?PHP
  $a=array("a"=>"red","b"=>"green","c"=>"red");
  print_r(array_unique($a));

  Output:  Array ( [a] => red [b] => green )
 //The array_unique() function removes duplicate values from an array.
?>
----------------------------------------------------------------------------------------------------------------------------------
Export :
SQL :
<?PHP
    $con = mysql_connect("localhost", "root", "");
    if (!$con) {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("abc", $con);
     $tables='*';
     if ($tables == '*') {
            $tables = array(              
            );
            $result = mysql_query('SHOW TABLES');
            while ($row = mysql_fetch_row($result)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',', $tables);
        }

        //cycle through
        foreach ($tables as $table) {
            $result = mysql_query('SELECT * FROM ' . $table); //exit;
            $num_fields = mysql_num_fields($result);

            $return.= 'DROP TABLE ' . $table . ';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
            $return.= "\n\n" . $row2[1] . ";\n\n";

            for ($i = 0; $i < $num_fields; $i++) {
                while ($row = mysql_fetch_row($result)) {
                    $return.= 'INSERT INTO ' . $table . ' VALUES(';
                    for ($j = 0; $j < $num_fields; $j++) {
                        $row[$j] = addslashes($row[$j]);
                        if (isset($row[$j])) {
                            $return.= '"' . $row[$j] . '"';
                        } else {
                            $return.= '""';
                        }
                        if ($j < ($num_fields - 1)) {
                            $return.= ',';
                        }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }

        //save file
        $Sql_file_name = 'sql_backup' . (date('Y-m-d_H-i-s'));
        $handle = fopen('sql_backup/'.$Sql_file_name . '.sql', 'w+');
        fwrite($handle, $return);
     
        mysql_close($con);
?>

Excel :
<table border="1" width="100%">
        <tr>
            <th>Item Name</th>
            <th>Price</th>
        </tr>
        <?PHP foreach ($menu_list as $menu) { ?>
            <tr>
                <td><?PHP echo $menu['item_name']; ?></td>
                <td><?PHP echo $menu['price']; ?></td>
            </tr>
       <?PHP } ?>
    </table>
<?PHP
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=database.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
?>

Word :
<?php
       $content = 'This is test page';
       @header('Content-Type: application/msword');
       @header('Content-Length: '.strlen($content));
       @header('Content-disposition: inline; filename="testdocument.doc"');
       echo $content;
?>

PDF :
<?PHP
      include('html2fpdf.php');
      $pdf= new HTML2FPDF();
      $pdf->AddPage();
      $CASE_ID =  $_GET['id'];
      $con = mysql_connect("localhost","root","");

      if (!$con){
          die('Could not connect: ' . mysql_error());
     }
     mysql_select_db('abc');

     $strContent=" Export to pdf";

     $pdf->WriteHTML($strContent);

     $pdf->Output("$pdf_title_1.pdf");

     $filename = "$pdf_title_1.pdf";
     $filepath = 'http://localhost/lawfirm/pdf/';
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
     header("Content-Type: application/octet-stream");
     header("Content-Disposition: attachment; filename={$filename}");
     header("Content-Transfer-Decoding: binary");
     readfile($filepath.$filename);
?>
----------------------------------------------------------------------------------------------------------------------------------
Reduce Image Size:
<?php
     $name = '';
     $type = '';
     $size = '';
     $error = '';
     function compress_image($source_url, $destination_url, $quality) {
           $info = getimagesize($source_url);
            if ($info['mime'] == 'image/jpeg')
                $image = imagecreatefromjpeg($source_url);
           elseif ($info['mime'] == 'image/gif')
               $image = imagecreatefromgif($source_url);
          elseif ($info['mime'] == 'image/png')
               $image = imagecreatefrompng($source_url);
          imagejpeg($image, $destination_url, $quality);
         return $destination_url; } if ($_POST)
        {
           if ($_FILES["file"]["error"] > 0)
            {
               $error = $_FILES["file"]["error"];          
           }
           else if
                (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg"))
                {
                      $url = $_FILES["file"]["name"];
                      $filename = compress_image($_FILES["file"]["tmp_name"], $url, 30);
                      $buffer = file_get_contents($url); /* Force download dialog... */                              
                }else {
                     $error = "Uploaded image should be jpg or gif or png";                  
               }
         }
  ?>
<html>
    <head>
        <title>Php code compress the image</title>
    </head>
    <body>
        <div class="message">
            <?php if($_POST){ if ($error) { ?>
            <label class="error"><?php echo $error; ?></label>
                <?php } } ?>
        </div>
        <fieldset class="well">
            <legend>Upload Image:</legend>
            <form action="" name="myform" id="myform" method="post" enctype="multipart/form-data">
                <ul>
                    <li>
                        <label>Upload:</label>
                        <input type="file" name="file" id="file"/>
                    </li>
                    <li>
                        <input type="submit" name="submit" id="submit" class="submit btn-success"/>
                    </li>
                </ul>
            </form>
        </fieldset>
    </body>
</html>

----------------------------------------------------------------------------------------------------------------------------------
Any Date-Time format to display Date(07 Dec 1988) Format :
              <?php echo date('d M Y', strtotime("1988-12-07 11:28:29")); ?>
              Output : 07 Dec 1988
----------------------------------------------------------------------------------------------------------------------------------
  Current Date/Day in Different Format :
  $Current_Day = date("l"); // get current day => Tuesday
  $Current_Date = date("Y-m-d"); // get current date => 2014-12-07

----------------------------------------------------------------------------------------------------------------------------------
Send SMS :
              $MSG = "Hi, Hi";
              $curl = curl_init();
              curl_setopt ($curl, CURLOPT_URL, "http://sms6.routesms.com:80/bulksms/bulksms?    username=a&password=1&type=0&dlr=1&destination=9874563210&source=ABC&message=$MSG");             curl_exec ($curl);
              curl_close ($curl);

----------------------------------------------------------------------------------------------------------------------------------
Send Mail :

Core PHP Send Mail :
    <?PHP
          $name=$_POST[name];
          $company_name=$_POST[company];
          $title=$_POST[title];
          $phone=$_POST[phone];
          $email=$_POST[emailID];
          $message="
               <tr><td>Name</td><td>$name</td></tr>
               <tr><td>Company</td><td>$company_name</td></tr>
               <tr><td>Title</td><td>$title</td></tr>
               <tr><td>Phone</td><td>$phone</td></tr>
               <tr><td>Email Id </td><td>$email</td></tr>";

        $to="test@test.com,abc@abc.com";
        $subject="Website Visitor";
        $headers  = 'From: '.$email." \n";
        $headers .= 'MIME-Version: 1.0' ."\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        mail($to,$subject,$message,$headers);
?>

----------------------------------------------------------------------------------------------------------------------------------
Print Section:
<html>
  <head>
     <script type="text/javascript">  
        function PrintDiv() {    
           var divToPrint = document.getElementById('divToPrint');
           var popupWin = window.open('', '_blank', 'width=300,height=300');
           popupWin.document.open();
           popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
            popupWin.document.close();
                }
     </script>
   </head>
        <body >
                other contents
            <div id="divToPrint" >
               <div style="width:200px;height:300px;background-color:teal;">
                  This is the div to print
                </div>
            </div>
            <div>
                <input type="button" value="print" onclick="PrintDiv();" />
            </div>
        </body>
</html>
----------------------------------------------------------------------------------------------------------------------------------
Text Show In Marathi To HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
----------------------------------------------------------------------------------------------------------------------------------
Text Insert In Marathi To Database:
ALTER TABLE display_data MODIFY discription VARCHAR(20) CHARACTER SET UTF8;
----------------------------------------------------------------------------------------------------------------------------------
 URL Redirect Non-www to www: 
<?PHP
    function curPageURL() {
        $pageURL = 'http';
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
          $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
          $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    $url_type = curPageURL();
        if($url_type=='http://rajeshpalande.com'){
        redirect("http://www.rajeshpalande.com");
    }
   
?>

----------------------------------------------------------------------------------------------------------------------------------
 Web site search meta key word:
  <meta charset="utf-8" name="keywords" content="Rajesh Palande.| www.rajeshpalande.com | Resume">
  <meta name="description" content="Rajesh Palande.| www.rajeshpalande.com">
  <meta name="author" content="Rajesh Palande.">
----------------------------------------------------------------------------------------------------------------------------------
Multiple File(value in array) To Store Folder And Database:
View :
<input type="file" name="attachFile[]" id="attachFile" style="width:80%" class="form-control"/>

Controllers :
        $fileArray = $_FILES["attachFile"]["name"];
        $fileTempName = $_FILES["attachFile"]["tmp_name"];

       for($i=0;$i<count($fileArray);$i++){
                $strFile[$i] = str_replace(" ", "_", $fileArray[$i]);
                move_uploaded_file($fileTempName[$i],"uploads/sendMailDoc/" . $strFile[$i]);
               
                $formValues = array(
                    'sendmail_id' => $send_id,
                    'doc_name' => $strFile[$i]
                );
                $tablename = "email_send_attach_document";
                $this->home_model->tableInsert($tablename, $formValues);
      } 

----------------------------------------------------------------------------------------------------------------------------------
Ajax :
  • Click Event :
     //click base to class
     $(document).ready(function(){
          $( ".returned" ).click(function() {
                 var returned_id = $(this).val();
                 var notice_id = $(this).attr("NI");
                 var document_transfer_id = $(this).attr("dti");
                   $.ajax({
                      url: "<?php echo base_url(); ?>notice/getReturnedUpdateDocumentTransfer",
                      type: 'POST',
                      data: 'returned=' + returned_id + "&document_transfer_id=" + document_transfer_id ,
                      success: function(msg) {
                              $('#documentTransferDiv').html(msg);
                      }
                });
          });
   });

                                                                 OR
   $(document).ready(function(){
          $( ".returned" ).click(function() {
                   $.post("<?php echo base_url();?>notice/getReturnedUpdateDocumentTransfer",   { returned:returned_iddocument_transfer_id:document_transfer_id  },function(data){
                              $('#documentTransferDiv').html(data);
                  });
           });
   });

   //click base to function
    function Get_primary_Email_Data(id){        
        var Email_Data = 'Email_ID=' + id;        
        $.ajax({
            url: "<?php echo base_url(); ?>home/get_email_address",
            type: 'POST',
            data: Email_Data,
            success: function(msg) {
                $('#PRIMARY_EMAIL').val(msg);
            }
        });
    }
  • Press To Enter Event :
      $(document).ready(function(){
              $('.search_txtbox1').keypress(function(e) {
                if(e.which == 13) {
                    var txtCuisine1=$('#txtCuisine1').val();
                    var txtCuisine2=$('#txtCuisine2').val();

                    if(txtCuisine1.length == 0) {  //for checking 3 characters
                        $('#restaurant_search_result').html("");
                    }

                    $('#restaurant_search_result').html("");
                    //loading image
                    $('#restaurant_search_result').html('<center><img src="<?php echo base_url(); ?>images/progress.gif"/></center>');
                    $.ajax({
                        url: "<?php echo base_url(); ?>pilot/restaurant_search_details",
                        type: 'POST',
                        data: 'cuisine1='+txtCuisine1+'&cuisine2='+txtCuisine2,
                        success: function(msg) {
                            $('#restaurant_search_result').html(msg);
                        }
                    });
                }
            });
        });
  • On Key Up Event :
      $(document).ready(function(){
              $(".search_txtbox1").keyup(function(){
                    var txtCuisine1=$('#txtCuisine1').val();
                    var txtCuisine2=$('#txtCuisine2').val();

                    if(txtCuisine1.length == 0) {  //for checking 3 characters
                        $('#restaurant_search_result').html("");
                    }

                    $('#restaurant_search_result').html("");
                    //loading image
                    $('#restaurant_search_result').html('<center><img src="<?php echo base_url(); ?>images/progress.gif"/></center>');
                    $.ajax({
                        url: "<?php echo base_url(); ?>pilot/restaurant_search_details",
                        type: 'POST',
                        data: 'cuisine1='+txtCuisine1+'&cuisine2='+txtCuisine2,
                        success: function(msg) {
                            $('#restaurant_search_result').html(msg);
                        }
                    });
            });
        });
  • Form Validation :
      <form name="add_new_address" id="add_new_address">
                  <div id="formMsg"></div>
                  <div class="form_element">
                        <input type="text" class="name_txtbox" name="wing" id="wing" placeholder="Plot/Wing"/>
                        <input type="text" class="name_txtbox margin_left_22" name="flat_no" id="flat_no"                                              placeholder="Flat No" style="border:1px solid red">
                    </div>
                 <div class="bottom_container" style="margin-top: 50px;">
                     <button class="nxt_btn alignright" type="button" id="btnAddNos">Add Address</button>
                </div>
      </form>

<script type="text/javascript">
$(document).ready(function(){        
            $("#btnAddNos").click(function(){
                    //validation part
                    if(!$("#flat_no").val()){
$("#flat_no").css({"border":"1px solid red"});
$("#flat_no").focus();
return false;
                  }else{
$("#flat_no").css({"border":"1px solid #333333"});
                }

                 var form_lenth = $("#flat_no").val().length;
                 if(form_lenth == '10'){
                     $("#flat_no").css({"border":"1px solid #999999"});
              }else{
                   $("#flat_no").css({"border":"1px solid red"});
                   $("#flat_no").focus();
                   return false;
             }

               var form_details=$("#add_new_address").serialize();

               $("#formMsg").html('<img src="<?php echo base_url();?>images/loader.gif">');

               $.ajax({
                      url: "<?php echo base_url();?>pilot/addNewAddress",
                      type: 'POST',
                      data: form_details,
                      success: function(msg) {
                           if(msg=="SUCCESS"){
                                $("#formMsg").html("<font color='green'>New Address added successfully</font>");
                            }
                            if(msg=="FAILED"){
                $("#formMsg").html("<font color='red'>Oops.. Something went wrong.</font>");
                         }
                      }
               });
          });
    });
</script>
  • Jquery Validation with Regular Expressions :    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>
    <script src="jquery.validate.js" type="text/javascript"></script>

   
   <script type="text/javascript">
   
     $(document).ready(function() {
       
        $.validator.addMethod("email", function(value, element) { 
            return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value); 
        }, "Please enter a valid email address.");       
        $.validator.addMethod("username",function(value,element){
            return this.optional(element) || /^[a-zA-Z0-9._-]{3,16}$/i.test(value); 
        },"Username are 3-15 characters");               
        $.validator.addMethod("password",function(value,element){
            return this.optional(element) || /^[A-Za-z0-9!@#$%^&*()_]{6,16}$/i.test(value); 
        },"Passwords are 6-16 characters");
       
        // Validate signup form
        $("#signup").validate({
            rules: {
                email: "required email",
                username: "required username",
                password: "required password"               
            },
            submitHandler: function() {                               
              $(".message").html('<center><img src="<?php echo base_url(); ?>images/progress_bar.gif"/></center>');
                var dataString = $("#add_appointment").serialize();
                $.ajax({
                    url: "<?php echo base_url(); ?>dashboard/addAppointment",
                    type: 'POST',
                    data: dataString,
                    success: function(msg) {
                        $(".message").html(msg);
                        resetForm("add_appointment");
                        window.location.reload(true);
                    }
                });
            }
        });
    });
   
    /**
    * This function clear all input fields value except button, submit, reset, hidden fields in different way
    * */
    function resetForm(formid){
        form = $('#'+formid);
        element = ['input','select','textarea'];

        for(i=0; i<element.length; i++){
            $.each( form.find(element[i]), function(){     
                switch($(this).attr('type')) {
                    case 'text':
                    case 'select':
                    case 'textarea':
                    case 'hidden':
                    case 'file':
                        $(this).val('');break;
                    case 'checkbox':
                    case 'radio':
                        $(this).attr('checked',false);break;
                    case 'select':
                        $(this).attr('selected',false);
                        break;
                }
            });
        }
    }
   
</script>
   
<style>
  input {
    width:220px;
    height:25px;
    font-size:13px;
    margin-bottom:10px;
    border:solid 1px #333333;   
 }
 label.error {   
    font-size:11px;
    background-color:#cc0000;
    color:#FFFFFF;
    padding:3px;
    margin-left:5px;
    -moz-border-radius: 4px;
   -webkit-border-radius: 4px;
}       
</style>


    <form method="post" action="jqueryregthank.html" name="signup" id="signup">
        <b>Email</b><br />
        <input type="text" name="email" id='email'/><br />           
        <b>UserName</b><br />
        <input type="text" name="username" id="username" /><br />
        <b>Password</b><br />
        <input type="password" name="password"  id="password" /><br /><br />
        <input type="submit" value=" Sign-UP " name='SUBMIT' id="SUBMIT"/>
    </form>
Ajax Success function  redirect to other location/page :  


 success: function(msg) {
         window.location.replace("<?PHP echo base_url(); ?>home/User");
 }
----------------------------------------------------------------------------------------------------------------------------------
Get Unique value from multi dimension array:

$unique = array_map('unserialize', array_unique(array_map('serialize', $data['news_comment_list'])));
----------------------------------------------------------------------------------------------------------------------------------
Get Common value in two array:

foreach($userlists_F as $key=>$val){
     if(in_array($val,$userlists_T)){
          $final_array[] = $val;
    }
 }
------------------------------------------------------------------------------------------------------------------------------

Merge multidimensional two array php:

$arrayMergeMulti = array_merge_recursive($karray, $varray);

----------------------------------------------------------------------------------------------------------------------------------

Replace Multidimention two array php:

$arrayReplaceMulti = array_replace_recursive($karray, $varray);

----------------------------------------------------------------------------------------------------------------------------------  

Get Random Value  By Use mt_rand function:
 $useChars='AEUYBDGHJLMNPQRSTVWXZ123456789';
            $track_id = $useChars{mt_rand(0,29)};
            for($i=1;$i<10;$i++) {
                $track_id .= $useChars{mt_rand(0,29)};
                }
            $pass                   = $track_id; 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

Foreach function merge array :
$ra = 1;
          foreach ($newsArray as $newsValue) {
              if($ra == 1){
                  $newArr = array();
                  $news_new_array = array_merge($newsValue, $newArr);
              } else {
                   $news_new_array = array_merge($newsValue, $news_new_array);
              }
            $ra++;
          }

    print_r($news_new_array);

------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

Difference between current time & actual time of post :
<?PHP
$today      = date('m/d/Y H:i:s', time());                                                   
 $to_time    = strtotime($note_list['date_time']);
$from_time  = strtotime($today);
 $startMinutes = $to_time - $from_time;
echo secondsToTime($startMinutes)." ago";

function secondsToTime($seconds) {
        $dtF = new DateTime("@0");
        $dtT = new DateTime("@$seconds");
        return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes %s seconds');
    }
output : 0 days, 4 hours, 25 minutes 58 seconds ago
?>
------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
Get time as per ip/country location :
insert time is gmdate("m/d/Y h:i:s");

$ip = "27.54.160.0";
$loginUrl = "http://freegeoip.net/json/".$ip; //put ip value here
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$result = curl_exec($ch);
curl_close($ch);
$data = json_decode($result, true);              
$timezoneshow= $data['time_zone']; // get time zone
                                           
$system_timezone = date_default_timezone_get();
date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");
$local_timezone = $timezoneshow;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");
date_default_timezone_set($system_timezone);
$diff = (strtotime($local) - strtotime($gmt));
$date = new DateTime($history['date_time']);
$date->modify("+$diff seconds");
$history_timestamp_new = $date->format("d M Y H:i:s");
echo date("d M Y H:i:s", strtotime($history_timestamp_new)); 
//output : 29 May 2015 13:31:10
------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
IP address to get details :
Type 1:
---------------------
$ip = "66.96.147.144";
$geoPlugin_array = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $ip) );
echo '<pre>';
print_r($geoPlugin_array);

OUTPUT :
Array
(
    [geoplugin_request] => 66.96.147.144
    [geoplugin_status] => 200
    [geoplugin_credit] => Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.
    [geoplugin_city] => Burlington
    [geoplugin_region] => MA
    [geoplugin_areaCode] => 781
    [geoplugin_dmaCode] => 506
    [geoplugin_countryCode] => US
    [geoplugin_countryName] => United States
    [geoplugin_continentCode] => NA
    [geoplugin_latitude] => 42.5051
    [geoplugin_longitude] => -71.204697
    [geoplugin_regionCode] => MA
    [geoplugin_regionName] => Massachusetts
    [geoplugin_currencyCode] => USD
    [geoplugin_currencySymbol] => $
    [geoplugin_currencySymbol_UTF8] => $
    [geoplugin_currencyConverter] => 1
)
-----------------------------------------------------------------------------------------------
Type 2:
---------------------
http://freegeoip.net/json/122.170.47.149

{"ip":"122.170.47.149","country_code":"IN","country_name":"India","region_code":"GJ","region_name":"Gujarat","city":"Ahmedabad","zip_code":"380025","time_zone":"Asia/Kolkata","latitude":23.033,"longitude":72.617,"metro_code":0}

$ip = "66.96.147.144";
$loginUrl = "http://freegeoip.net/json/".$ip;
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$result = curl_exec($ch);
curl_close($ch);
$data = json_decode($result, true);
echo "<pre>";
print_r($data);
OUTPUT :
Array
(
    [ip] => 66.96.147.144
    [country_code] => US
    [country_name] => United States
    [region_code] => MA
    [region_name] => Massachusetts
    [city] => Burlington
    [zip_code] => 01803
    [time_zone] => America/New_York
    [latitude] => 42.505
    [longitude] => -71.196
    [metro_code] => 506
)
------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
Base on latitude and longitude get address :
$lat = '42.505';
$lang = '-71.196';
$loginUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lang&sensor=true";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$result=curl_exec($ch);
curl_close($ch);
$data = json_decode($result, true);
echo $data['results'][0]['formatted_address'];
OUTPUT : 13 Bedford Street, Burlington, MA 01803, USA
------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
Call function or script after some time :
function getdata(){
setTimeout(function() {
     //code here
}, 500);
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
Access one controller function to other controller :
Main Controller Name Common 
--------------------------------------------
Class Common extends CI_Controller{
function getDateTime($dateTime){
return $dateTime;
}
}

When access getDateTime function in other controller (e.g. Home Controller)
---------------------------------------------------------------------------------------------------
require_once APPPATH.'controllers/common.php';
Class dashboard extends Common{
$dateTime = "07 Jul 2015 16:11:37";
$getDateTime = $this->getDateTime($dateTime);
}

When Access getDateTime function in View page
----------------------------------------------------------------
$dateTime = "07 Jul 2015 16:11:37";
$this->method_call = & get_instance();
$getDateTime = $this->method_call->getDateTime($dateTime);

-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Check Email :
<input type="text" class="form-control emailvalidate" name="email_id" id="email_id" onchange="return checkEmailger();" />
<input type="hidden" name="checkuniueness" id="checkuniueness" value="0"/>
<input type="hidden" name="checkvalid" id="checkvalid" value="0"/>

<script>
function checkEmailger() {
var email = $(".emailvalidate").val();
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
$('#emailvalidate').html("Invalid ID!");
$(".emailvalidate").css({"border": "1px solid red"});
$("#email_id").css({"border": "1px solid red"});
$("#email_id").focus();
$('#checkvalid').val('1');
return false;
} else { //if email id is exit in database then use else condition
$('#checkvalid').val('0');
var datastring = "email=" + email;
$.ajax({
url: "<?PHP echo base_url(); ?>home/check_email_duplicate", //this function to check email id exit then return msg "0" or not exit then return msg "1"
type: 'POST',
data: datastring,
success: function(msg){
if(msg == '0'){  //email id exit then give msg
$('#checkuniueness').val('1');
$('#emailvalidate').html("Email id already used.");
$('#emailvalidate').css({"color":"red"});
return false;
} else {
$('#checkuniueness').val('0');
$('#emailvalidate').html("");
$(".emailvalidate").css({"border": "1px solid #a9a9a9"});
return true;
}
}
});
}
}
</script>
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Upload Image File Then Create Thumb:
Write Code in Model :
function file_extension($filename){       
return end(explode(".", $filename));
}

function generatenamecode(){
$validchars[2] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghijklmnopqrstuvwxyz";
$namecode  = "";
$counter   = 0;
while ($counter <10) {
$actChar = substr($validchars[2], rand(0, strlen($validchars[2])-1), 1);
// All character must be different
if (!strstr($namecode, $actChar)) {
$namecode .= $actChar;
$counter++;
}
}
$datetime=strtotime(date("h:i:sa"));
global $filetime;
$namecode .=$filetime."". $datetime;
return $namecode;     
}

In Controller :
$output_dir         = "images/blog_img/";
$output_dir_thumb   = "images/blog_img/thumb/";
$output_dir_mid     = "images/blog_img/60_60/";
$fileName = $_FILES["blogimage"]["name"];

if (($_FILES['blogimage']['type'] == 'image/jpeg')  || ($_FILES["blogimage"]["type"] == "application/jpg") || ($_FILES["blogimage"]["type"] == "application/bmp") || ($_FILES["blogimage"]["type"] == "image/png") || ($_FILES["blogimage"]["type"] == "application/gif")|| ($_FILES["blogimage"]["type"] == "video/avi")|| ($_FILES["blogimage"]["type"] == "video/mp4")){
$file_ext1      = $this->home_model->file_extension($_FILES['blogimage']['name']);                   
$tpath          = $_FILES['blogimage']['tmp_name'];
$namecode       = $this->home_model->generatenamecode();
$new_picname1   = $output_dir."".$fileName;
$el_picname     = $output_dir_mid."".$fileName;
$th_picname     = $output_dir_thumb."".$fileName;

if(@copy($tpath,"$new_picname1")) {
list($width, $height) = getimagesize($tpath);
if($width>$height){
$desired_width    = 60;
$desired_height   = 60;
$desired_width_t  = 40;
$desired_height_t = floor($height*($desired_width_t/$width));                           
}else{
$desired_height     = 60;
$desired_width      = 60;
$desired_height_t   = 40;
$desired_width_t    = floor($width*($desired_height_t/$height));
}

if($file_ext1=='jpg') $rimage   = imagecreatefromjpeg($new_picname1);
if($file_ext1=='gif')$rimage    = imagecreatefromgif($new_picname1);
if($file_ext1=='png')$rimage    = imagecreatefrompng($new_picname1);
if($file_ext1=='jpeg')$rimage   = imagecreatefromjpeg($new_picname1);

$image_e = imagecreatetruecolor($desired_width, $desired_height);
imagecopyresampled($image_e, $rimage, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
imagejpeg($image_e, "$el_picname", 80);
imagegif($image_e, "$el_picname", 80);
imagepng($image_e, "$el_picname", 80);
imagedestroy($image_e);

//thmbimage
$image_t = imagecreatetruecolor($desired_width_t, $desired_height_t);
imagecopyresampled($image_t, $rimage, 0, 0, 0, 0, $desired_width_t, $desired_height_t, $width, $height);
imagejpeg($image_t, "$th_picname", 80);
imagegif($image_t, "$tl_picname", 80);
imagepng($image_t, "$tl_picname", 80);
imagedestroy($image_t);

//remove tempfile
imagedestroy($rimage);
unlink($new_picname);
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Google Maps Multiple Markers :
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    
    var locations = [
      ['Andheri', 19.11365, 72.86973, 5],
      ['Malad 123', 19.1870, 72.8489, 4],
      ['Borivali', 19.23719, 72.84414, 3],
      ['Navi Mumbai', 19.03305,    73.02966, 2],
      ['Mumbai', 19.0759837,  72.8776559, 1]];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(19.0759837,  72.8776559),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------------
To avoid blank link(#) :
<a href="javascript:void(0);">Home</a>
------------------------------------------------------------------------------------------------------------------------------------------------
Convert Special Character (#,%) In File Name(Image) :
function validateimage($imagename) {
$explode = explode(".", $imagename);
$extension = $explode[1];
if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'PNG' || $extension == 'bmp' || $extension == 'BMP' || $extension == 'GIF') {
if (strpos($imagename, '%') !== false && strpos($imagename, '%25') === false) {
return $imagenameaa = str_replace("%", "%25", $imagename);
} else if (strpos($imagename, '#') !== false && strpos($imagename, '%23') === false) {
return $imagenameaa = str_replace("#", "%23", $imagename);
} else {
return $imagenameaa = $imagename;
}
} else {
return $imagenameaa = 'No_Image.jpg';
}
}
------------------------------------------------------------------------------------------------------------------------------------------------
Create thumbnail image while uploading video:
<html>
    <head>
        <title>Create thumbnail image while uploading video </title>
    </head>
    <body>
        <form action="upload_video.php" enctype="multipart/form-data" method="post" >
            Video Upload :
            <input type="file" name="myfile" id="myfile" />
            <input type="submit" name="submit" id="submit"/>
        </form>
    </body>
</html>

upload_video.php File
<?PHP
$output_dir = "images/user_videos/";

$error = $_FILES["myfile"]["error"];

$imageExtention = explode(".", $_FILES['myfile']['name']);
if ($imageExtention[1] == 'avi' || $imageExtention[1] == 'mp4') {
    //$namecode=$this->home_model->generatenamecode();   
    $namecode = "123";
    $fileName = $namecode . '' . $_FILES["myfile"]["name"];

    move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $fileName);
    $ffmpeg = 'ffmpeg';
    $video = 'images/user_vedios/' . $fileName;
    $imagename_check = explode(".", $fileName);
    $nameof_img = $imagename_check[0];

    $extension = $nameof_img[1];
    $image = 'images/user_vedios/video_imges/' . $nameof_img . '.png';
    $second = 5;
    // get the duration and a random place within that
    $cmd = "$ffmpeg -i $video 2>&1";
    if (preg_match('/Duration: ((\d+):(\d+):(\d+))/s', `$cmd`, $time)) {
        $total = ($time[2] * 3600) + ($time[3] * 60) + $time[4];
        $second = rand(1, ($total - 1));
    }

    // get the screenshot
    $cmd = "$ffmpeg -i $video -deinterlace -an -ss $second -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg $image 2>&1";

    $return = `$cmd`;
    $videosize = $_FILES["myfile"]["size"];
    echo $fileName . ',' . $videosize;
} else {
    echo '0';
}

?>
------------------------------------------------------------------------------------------------------------------------------------------------
PHP Click Event File Download Script:
Download
------------------------------------------------------------------------------------------------------------------------------------------------
Base on two latitude and longitude get estimated time and distance:
<?PHP
$lat1 = "19.1870"; //Malad(Mumbai)
$long1 = "72.8489"; //Malad(Mumbai)

$lat2 = "19.1190"; //Andheri(Mumbai)
$long2 = "72.8470"; //ndheri(Mumbai)
//$dist = $this->GetDrivingDistance($lat1, $long1, $lat2, $long2); //when using codeigniter
$dist = GetDrivingDistance($lat1, $long1, $lat2, $long2); //php
echo 'Distance: <b>'.$dist['distance'].'</b><br>Travel time duration: <b>'.$dist['time'].'</b>';

function GetDrivingDistance($lat1, $long1, $lat2, $long2){
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['text'];
return array('distance' => $dist, 'time' => $time);
}
Output:
Distance: 8,8 km

Travel time duration: 34 min
------------------------------------------------------------------------------------------------------------------------------------------------
Download Project Backup in xampp/htdocs folder:
Hit URL : localhost/ProjectFileName/ControllerName/backup(function Name)
function  backup(){            
$this->load->library('zip');
$path='D:\\xampp\\htdocs\\ProjectFileName\\';
$this->zip->read_dir($path); 
$this->zip->download('ProjectFileName.zip');
}
------------------------------------------------------------------------------------------------------------------------------------------------
Date different :
Compare Database Date To Current Date: 
--------------------------------------------------------
$todayDate_  = strtotime(date('d-m-Y'));
$uploadDate = $history['date_time'];
$dates = strtotime(date("d-m-Y",strtotime("$uploadDate")));
if ($todayDate_ == $dates ) {
}

Compare Date In Between To Current Date:
-----------------------------------------------------------
$todayDate  = strtotime(date('Y-m-d'));
$date       = $todayDate;
$date2      = strtotime($ADSvalue_720_90['adsstartdate']);
$date3      = strtotime($ADSvalue_720_90['adsenddate']);
if ($date >= $date2 && $date <= $date3) {
}

Calculate Year In PHP:
------------------------------
$birthDate = "Dec 07, 1988";
$from               = new DateTime($birthDate);
$to                 = new DateTime('today');
$ageCount           = $from->diff($to)->y;
echo "Ans = ".$ageCount; //Ans = 27
------------------------------------------------------------------------------------------------------------------------------------------------
Clear cache in core PHP :
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
------------------------------------------------------------------------------------------------------------------------------------------------
Share url link to social sites :
Facebook Share: 
--------------------------------------------------------
<a data-original-title="Facebook" rel="tooltip" target="_blank" href='https://www.facebook.com/sharer/sharer.php?u=http://usehoga.blogspot.in/'> Facebook </a>

Twitter Share:
-----------------------------------------------------------
<a data-original-title="Twitter" rel="tooltip" target="_blank" href="https://twitter.com/intent/tweet?text=http://usehoga.blogspot.in/"> Twitter </a>

LinkedIn Share:
------------------------------
<a data-placement="left" target="_blank"  data-original-title="LinkedIn" rel="tooltip" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http://usehoga.blogspot.in/" target="_blank"> LinkedIn </a>

Google+ Share:
------------------------------
<a class="btn btn-google btn-xs m_bot5 m_top5" data-original-title="Google+"  target="_blank" rel="tooltip" href="https://plus.google.com/share?url=http://usehoga.blogspot.in/" > Google+ </a>
------------------------------------------------------------------------------------------------------------------------------------------------
Onclick javascript to make browser go back to previous page :

<input action="action" type="button" value="Back" onclick="history.go(-1);" />

------------------------------------------------------------------------------------------------------------------------------------------------

2 comments:

  1. Nice blog. MSgClub SMS API PHP send a text message directly from your own software, website or application which developed using php code is now gets possible. Your search for sending information from a reliable and robust application will get end here because MsgClub is helping api users.
    www.msgclub.net/sms-api/php-api.aspx

    ReplyDelete
  2. Nice blog this blog is very help full to new php developer

    ReplyDelete