Monday 18 July 2016

get time between two different locations using latitude and longitude in php

Get time between two different locations using latitude and longitude in php

<?php

$url ="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=16.538048,80.613266&destinations=23.0225,72.5714";



$ch = curl_init();
// Disable SSL verification

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

$result_array=json_decode($result);

//print_r();
echo "<pre>";
print_r($result_array->rows[0]->elements[0]->duration->text);

Wednesday 29 June 2016

Displaying a flash message after redirect in Codeigniter

Displaying a flash message after redirect in Codeigniter


In Your Controller set this
<?php

public function change_password(){







if($this->input->post('submit')){
$change = $this->common_register->change_password();

if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);



redirect('controllername/methodname','refresh');
}

?>

In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
  window.setTimeout(function() {
    $(".alert").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove();
    });
}, 4000);
});
</script>

<?php

if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>

</div>
<?php
}

?>

Sunday 19 June 2016

adding multiple markers to google maps using javascript and php

Adding multiple markers to google maps using javascript and php

adding multiple markers to google maps using javascript and php
Please Check Below File

Create map3.php File same as here

$conn = mysql_connect("localhost","root","");

mysql_select_db('yourdatabase');

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}

$query = mysql_query("select * from yourtable");



//header("Content-type: text/html");

/* Get lat and Lan using table query */
$i=0;

while($row = mysql_fetch_assoc($query)){
   

$reposnse['markers'][$i]['lat']= $row['lat'];
$reposnse['markers'][$i]['lag']= $row['lag'];


$i++;
}

echo json_encode($reposnse);
?>

After create map2.php same as here

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

    <script type="application/javascript">

  

     

     $(document).ready(function(e) {
       


$.ajax({
url:"map3.php",
dataType: 'json',
success: function(result){
var html = '<markers>';


for (var prop in result['markers']) {

var value = result['markers'][prop];
//alert(value.lat);
html += '<marker ';
html += 'lat="';
html += value.lat+'"';
html += 'lng="';
html += value.lag+'"';
html += '/>';
}
html += '</markers>';
$('#test').html(html);

function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 6,
            center: new google.maps.LatLng(15.317277,75.71389),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

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

        var marker;

        var location = {};


var markers = document.getElementsByTagName("marker");


        for (var i = 0; i < markers.length; i++) {

//alert(markers[i].getAttribute("lat"));
            location = {
                name : 'test'+i,
                address : 'baglore',
                city : 'bangalore',
                state : 'Karnataka',
                zip : '560017',
                pointlat : parseFloat(markers[i].getAttribute("lat")),
                pointlng : parseFloat(markers[i].getAttribute("lng"))  
            };

            console.log(location);

            marker = new google.maps.Marker({
                position: new google.maps.LatLng(location.pointlat, location.pointlng),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function(marker,location) {
                return function() {
                    infowindow.setContent(location.name);
                    infowindow.open(map, marker);
                };
            })(marker, location));
        }
  }

    google.maps.event.addDomListener(window, 'load', initialize);

},
});

    });
 
    </script>
</head>
<body>
    <div id="test">
    </div>

    <div id="map" style="width: 500px; height: 400px;"></div>
</body>
</html>

adding multiple markers to google maps using javascript and php

Friday 27 May 2016

Get geo location with latitude and lagitaure and address in javascript using browser

Get geo location with latitude and lagitaure and address in javascript using browser

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="application/javascript">

function GetAddress(lat,long) {
            var lat = parseFloat(lat);
            var lng = parseFloat(long);
            var latlng = new google.maps.LatLng(lat, lng);
            var geocoder = geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        alert("Location: " + results[1].formatted_address);
                    }
                }
            });
        }
function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
 
  console.log(position);
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

   // var img = new Image();
    //img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

//var test = "http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true";
//console.log(test);

GetAddress(latitude,longitude);

    //output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}
</script>

<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>

Monday 16 May 2016

List all the files and folders in a Directory csv(file) read with PHP recursive function


List all the files and folders in a Directory csv(file) read with PHP recursive function

<?php

/** List all the files and folders in a Directory csv(file) read with PHP recursive function */
function getDirContents($dir, &$results = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            //$results[] = $path;
        }
    }

    return $results;
}





$files = getDirContents('/xampp/htdocs/medifree/lab');//here folder name where your folders and it's csvfile;


foreach($files as $file){
$csv_file =$file;
$foldername =  explode(DIRECTORY_SEPARATOR,$file);
//using this get your folder name (explode your path);
print_r($foldername);

if (($handle = fopen($csv_file, "r")) !== FALSE) {

fgetcsv($handle); 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
}
fclose($handle);
}

}

?>

Tuesday 10 May 2016

Truncate all tables in a MySQL database in one command

Truncate all tables in a MySQL database in one command

SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') 
FROM INFORMATION_SCHEMA.TABLES where  table_schema in ('databasename1','databasename2');
 
if Cannot delete or update a parent row: a foreign key constraint fails
 
That happens if there are tables with foreign keys references to the table you are trying to drop/truncate.
Before truncating tables All you need to do is:
SET FOREIGN_KEY_CHECKS=0;
Truncate your tables and change it  back to 
SET FOREIGN_KEY_CHECKS=1; 

user this php code
<?php


mysql_connect("localhost","root",'');

mysql_select_db("restaurant");

$truncate = mysql_query("SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') as tables_query FROM INFORMATION_SCHEMA.TABLES where table_schema in ('restaurant')");


while($truncateRow=mysql_fetch_assoc($truncate)){

mysql_query($truncateRow['tables_query']);


}


?>
  

Thursday 5 May 2016

Create simple capcha in php with jquery validation

Create simple capcha in php with jquery validation

Create capcha code need three files

capcha.php
form.php
check-capcha.php

capcha.php

download font arial.ttf addded in fonts folder http://www5.miele.nl/apps/vg/nl/miele/mielea02.nsf/0e87ea0c369c2704c12568ac005c1831/07583f73269e053ac1257274003344e0?OpenDocument


<?php

session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {
    // this numbers refer to numbers of the ascii table (lower case)
    $string .= chr(rand(97, 122));
}

 $_SESSION['random_code'] = $string;

 $data['code'] = $string;
$dir = 'fonts/';

if(!is_dir($dir)){
mkdir($dir);
}

$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 200, 100, 90); // red
$white = imagecolorallocate($image, 255, 255, 255);

imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['random_code']);

$save= "test.png";
  imagepng($image,$save);
  ob_start();
    imagedestroy($image);
echo json_encode($data);
?>

 form.php

 <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js"></script>
<script type="application/javascript">
$(document).ready(function(e) {

$('#test').validate({
rules:{
capcha:{required: true,
remote: {
                    url: "check-capcha.php",
                    type: "post",
data:{hiddencapcha:function(){return $('#hidden_capcha').val()}}
                 }
}
},
messages:{
capcha:{
remote:"invalid capcha"
}
}
});
$.ajax({
url: "capcha.php",
success: function( result ) {
var newd = JSON.parse(result);

$('input[name=hidden_capcha]').val(newd.code);


$('#capchas').attr('src',"test.png?"+ new Date().getTime());
},error: function(){ alert(result)}
});
   
$('#generate_capcha').click(function(){

$.ajax({
url: "capcha.php",
success: function( result ) {
var newd = JSON.parse(result);

$('input[name=hidden_capcha]').val(newd.code);

$('#capchas').attr('src',"test.png?"+ new Date().getTime());
},error: function(){ alert(result)}
});
});

});

</script>

<form name="test" id="test">

<span id="capchas_images"><img id="capchas" src="test.png" /></span> <a href="javascript:void(0)" id="generate_capcha">Refresh</a>
<input type="text" name="capcha" />
<input type="hidden" name="hidden_capcha" id="hidden_capcha" />
</form>

check-capch.php

<?php


if($_POST['capcha']==$_POST['hiddencapcha'])
{
echo "true";
}else{
echo "false";
    }
?>

Tuesday 26 April 2016

Read More link in blog in php and Wordpress using Jquery


Read More link  in blog in php and Wordpress using Jquery

<script src="https://code.jquery.com/jquery-2.2.3.js"></script>
<script type="application/javascript">
jQuery(document).ready(function($) {



jQuery(document).on("click","a.less",function(event){

var href = jQuery(this).text();
if(href=="read more..."){

var moretext =jQuery(this).parent().parent().find('input[name=more]').val();
jQuery(this).parent().html(moretext);
}

if(href=="less"){

var lesstext =jQuery(this).parent().parent().find('input[name=less]').val();
jQuery(this).parent().html(lesstext);

}
return false;
event.preventDefault();

});
});
</script>
<?php

$string="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
?>
<div class="product_text">
                 
                   
<?php   $string = strip_tags($string)." <a class='less' href='javascript:void(0)'>less</a>";
$substr = substr($string, 0, strpos(wordwrap($string, 250), "\n"))." <a class='less' href='javascript:void(0)'>read more...</a>";
?>
                <input type="hidden" name="less" value="<?php echo $substr; ?>" />
                <input type="hidden" name="more" value="<?php echo $string; ?>" />

<?php

echo '<p class="readMore">'.$substr."</p>";


?>


                  
                  </div>

Thursday 21 April 2016

jquery Star rating plugin with php

 jquery Star rating plugin with php



 <script src="https://code.jquery.com/jquery-2.2.3.js"></script>
 <script type="application/javascript">
 $(document).ready(function(e) {
   $.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

$(function() {
    $('span.stars').stars();
});
});
 </script>



 <style>
  span.stars, span.stars span {
    display: block;
    background: url(images/stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

span.stars span {
    background-position: 0 0;
}
</style>

<!--  You can get avarage rating using php query get here where 3.5 -->

 <span class="stars">3.5</span>
 use this image for start rating
 https://drive.google.com/file/d/0BwNaFGxzigBud25jaG1XaWlfU0k/view?usp=sharing

Saturday 16 April 2016

Create Multiple Images Upload using Custom field or Meta box in Wordpress

Create Multiple Images Upload using Custom field or Meta box in Wordpress

<?php
/**
 * Plugin Name:       My Gallery
 */

add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );

function smashing_post_meta_boxes_setup(){
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
}

function smashing_add_post_meta_boxes(){
add_meta_box(
    'smashing-post-class',      // Unique ID
    esc_html__( 'Post Class', 'example' ),    // Title
    'smashing_post_class_meta_box',   // Callback function
    'post',         // Admin page (or post type)
    'normal',         // Context
    'default'         // Priority
  );
}


function smashing_post_class_meta_box($object){ ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>

 
  <p>
  </br>
  <label for="smashing-post-class"><?php _e( "Upload Your Image", 'example' ); ?></label>
  </br>
  <input type="file" id="wp_custom_attachment" name="wp_custom_attachment[]" multiple="multiple" size="25" />
  <br />
  <?php $imgs= get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

  $images=1;
$imgs=json_decode(base64_decode($imgs));
  if(count($imgs)>0){

  foreach ($imgs as $img){
   ?>

      <img src="<?php echo  $img; ?>" width="100px" height="100px"  />
      <?php if($images %4 ==0){ echo "<br>"; } ?>
    
    
<?php  $images++;} }
   ?>
  <input type="hidden" value="<?php echo base64_encode(json_encode($imgs)); ?>" name="save_images"/>
  </p>
  <?php
}


function smashing_save_post_class_meta( $post_id, $post ) {

if ( ! function_exists( 'wp_handle_upload' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

  /* Verify the nonce before proceeding. */
  if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
    return $post_id;

  /* Get the post type object. */
  $post_type = get_post_type_object( $post->post_type );

  /* Check if the current user has permission to edit the post. */
  if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
    return $post_id;

  /* Get the posted data and sanitize it for use as an HTML class. */
  $new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );


if(!empty($_FILES['wp_custom_attachment']['name'])) {
for($i=0;$i<=count($_FILES['wp_custom_attachment']['name']);$i++){

$_FILES['wp_custom_attachment']['name'][ $i ];
  if ( '' != $_FILES['wp_custom_attachment']['name'][ $i ] ) {

  $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'][ $i ], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name'][ $i ]));

if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
}
$images[] = $upload['url'];
  }




}

if(count($images)==0){
$images =$_POST['save_images'];
}else{
$images = base64_encode(json_encode($images));
}

   add_post_meta($post_id, 'wp_custom_attachment', $images);
    update_post_meta($post_id, 'wp_custom_attachment', $images); 

}

}

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');