Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

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);
}

}

?>

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

Tuesday 5 April 2016

Add Gallery as custom field in wordpress

Hello,

If you have gallery as custom field then see below example.
i have here application post type. i am implement galley save in this post. Please Check Below Code.

Add Gallery as custom field in wordpress 

This Is Your functions.php code

<?php
function plu_admin_enqueue() { 
   // if(!($condition_to_check_your_page))// adjust this if-condition according to your theme/plugin
     //  return;
    wp_enqueue_script('plupload-all');

    wp_register_script('myplupload',  get_stylesheet_directory_uri() .'/js/myplupload.js', array('jquery'));

    wp_enqueue_script('myplupload');

    wp_register_style('myplupload', get_stylesheet_directory_uri() .'/css/myplupload.css');
    wp_enqueue_style('myplupload');
}
add_action( 'admin_enqueue_scripts', 'plu_admin_enqueue' ); 


function plupload_admin_head() { 
// place js config array for plupload
    $plupload_init = array(
        'runtimes' => 'html5,silverlight,flash,html4',
        'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
        'container' => 'plupload-upload-ui', // will be adjusted per uploader
        'drop_element' => 'drag-drop-area', // will be adjusted per uploader
        'file_data_name' => 'async-upload', // will be adjusted per uploader
        'multiple_queues' => true,
        'max_file_size' => wp_max_upload_size() . 'b',
        'url' => admin_url('admin-ajax.php'),
        'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
        'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
        'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')),
        'multipart' => true,
        'urlstream_upload' => true,
        'multi_selection' => false, // will be added per uploader
         // additional post data to send to our ajax hook
        'multipart_params' => array(
            '_ajax_nonce' => "", // will be added per uploader
            'action' => 'plupload_action', // the ajax action name
            'imgid' => 0 // will be added per uploader
        )
    );
?>
<script type="text/javascript"> 
    var base_plupload_config=<?php echo json_encode($plupload_init); ?>;
</script> 
<?php 
}
add_action("admin_head", "plupload_admin_head");

function g_plupload_action() {

    // check ajax noonce
    $imgid = $_POST["imgid"];
    check_ajax_referer($imgid . 'pluploadan');

    // handle file upload
    $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action'));

    // send the uploaded file url in response
    echo $status['url'];
    exit;
}
add_action('wp_ajax_plupload_action', "g_plupload_action"); 


add_action('add_meta_boxes', 'add_upload_file_metaboxes');

function add_upload_file_metaboxes() {
    add_meta_box('swp_file_upload', 'File Upload', 'swp_file_upload', 'appilcations', 'normal', 'default');
}

function swp_file_upload() {
global $post;
 //$svalue =get_post_meta( get_the_ID(), 'img1', true );

 echo '<input type="hidden" name="podcastmeta_noncename" id="podcastmeta_noncename" value="'.
    wp_create_nonce(plugin_basename(__FILE__)).
    '" />';
    // Noncename needed to verify where the data originated
   
$id = "img1"; // this will be the name of form field. Image url(s) will be submitted in $_POST using this key. So if $id == “img1” then $_POST[“img1”] will have all the image urls

$svalue = ""; // this will be initial value of the above form field. Image urls.

$multiple = true; // allow multiple files upload

$width = null; // If you want to automatically resize all uploaded images then provide width here (in pixels)

$height = null; // If you want to automatically resize all uploaded images then provide height here (in pixels)
?>

<label>Upload Images</label> 
<input type="hidden" name="<?php echo $id; ?>" id="<?php echo $id; ?>" value="<?php echo get_post_meta( get_the_ID(), 'img1', true ); ?>" /> 
<div class="plupload-upload-uic hide-if-no-js <?php if ($multiple): ?>plupload-upload-uic-multiple<?php endif; ?>" id="<?php echo $id; ?>plupload-upload-ui"> 
    <input id="<?php echo $id; ?>plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" />
    <span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce($id . 'pluploadan'); ?>"></span>
    <?php if ($width && $height): ?>
            <span class="plupload-resize"></span><span class="plupload-width" id="plupload-width<?php echo $width; ?>"></span>
            <span class="plupload-height" id="plupload-height<?php echo $height; ?>"></span>
    <?php endif; ?>
    <div class="filelist"></div>
</div> 
<div class="plupload-thumbs <?php if ($multiple): ?>plupload-thumbs-multiple<?php endif; ?>" id="<?php echo $id; ?>plupload-thumbs"> 
</div> 
<div class="clear"></div>


<?php
//echo $svalue =get_post_meta( get_the_ID(), 'img1', true );
 }

function save_podcasts_meta($post_id, $post) {
    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if (!wp_verify_nonce($_POST['podcastmeta_noncename'], plugin_basename(__FILE__))) {
        return $post -> ID;
    }
    // Is the user allowed to edit the post?
    if (!current_user_can('edit_post', $post -> ID))
        return $post -> ID;
    // We need to find and save the data
    // We'll put it into an array to make it easier to loop though.
    $podcasts_meta['img1'] = $_POST['img1'];
    // Add values of $podcasts_meta as custom fields

    foreach($podcasts_meta as $key => $value) {
        if ($post -> post_type == 'revision') return;
         $value = implode(',', (array) $value);
 
        if (get_post_meta($post -> ID, $key, FALSE)) { // If the custom field already has a value it will update
            update_post_meta($post -> ID, $key, $value);
        } else { // If the custom field doesn't have a value it will add
            add_post_meta($post -> ID, $key, $value);
        }
        if (!$value) delete_post_meta($post -> ID, $key); // Delete if blank value
    }
}
add_action('save_post', 'save_podcasts_meta', 1, 2); // sav

added myplupload.js and myplupload.css in your theme folder.

myplupload.js code

    jQuery.fn.exists = function() { 
        return jQuery(this).length > 0;
    }
    jQuery(document).ready(function($) {
    
        if ($(".plupload-upload-uic").exists()) {
            var pconfig = false;
            $(".plupload-upload-uic").each(function() {
                var $this = $(this);
                var id1 = $this.attr("id");
                var imgId = id1.replace("plupload-upload-ui", "");
    
                plu_show_thumbs(imgId);
    
                pconfig = JSON.parse(JSON.stringify(base_plupload_config));
    
                pconfig["browse_button"] = imgId + pconfig["browse_button"];
                pconfig["container"] = imgId + pconfig["container"];
                pconfig["drop_element"] = imgId + pconfig["drop_element"];
                pconfig["file_data_name"] = imgId + pconfig["file_data_name"];
                pconfig["multipart_params"]["imgid"] = imgId;
                pconfig["multipart_params"]["_ajax_nonce"] = $this.find(".ajaxnonceplu").attr("id").replace("ajaxnonceplu", "");
    
                if ($this.hasClass("plupload-upload-uic-multiple")) {
                    pconfig["multi_selection"] = true;
                }
    
                if ($this.find(".plupload-resize").exists()) {
                    var w = parseInt($this.find(".plupload-width").attr("id").replace("plupload-width", ""));
                    var h = parseInt($this.find(".plupload-height").attr("id").replace("plupload-height", ""));
                    pconfig["resize"] = {
                        width: w,
                        height: h,
                        quality: 90
                    };
                }
    
                var uploader = new plupload.Uploader(pconfig);
    
                uploader.bind('Init', function(up) {
    
                });
    
                uploader.init();
    
                // a file was added in the queue
                uploader.bind('FilesAdded', function(up, files) {
                    $.each(files, function(i, file) {
                        $this.find('.filelist').append('
' +
    
                        file.name + '
(' + plupload.formatSize(0) + '/' + plupload.formatSize(file.size) + ') ' + '
');
                    });
    
                    up.refresh();
                    up.start();
                });
    
                uploader.bind('UploadProgress', function(up, file) {
    
                    $('#' + file.id + " .fileprogress").width(file.percent + "%");
                    $('#' + file.id + " span").html(plupload.formatSize(parseInt(file.size * file.percent / 100)));
                });
    
                // a file was uploaded
                uploader.bind('FileUploaded', function(up, file, response) {
    
    
                    $('#' + file.id).fadeOut();
                    response = response["response"]
                    // add url to the hidden field
                    if ($this.hasClass("plupload-upload-uic-multiple")) {
                        // multiple
                        var v1 = $.trim($("#" + imgId).val());
                        if (v1) {
                            v1 = v1 + "," + response;
                        } else {
                            v1 = response;
                        }
                        $("#" + imgId).val(v1);
                    } else {
                        // single
                        $("#" + imgId).val(response + "");
                    }
                    // show thumbs
                    plu_show_thumbs(imgId);
                });
            });
        }
    });
    
    function plu_show_thumbs(imgId) { 
        var $ = jQuery;
        var thumbsC = $("#" + imgId + "plupload-thumbs");
        thumbsC.html("");
        // get urls
        var imagesS = $("#" + imgId).val();
        var images = imagesS.split(",");
        for (var i = 0; i < images.length; i++) {
            if (images[i]) {
                var thumb = $('
');
                thumbsC.append(thumb);
                thumb.find("a").click(function() {
                    var ki = $(this).attr("id").replace("thumbremovelink" + imgId, "");
                    ki = parseInt(ki);
                    var kimages = [];
                    imagesS = $("#" + imgId).val();
                    images = imagesS.split(",");
                    for (var j = 0; j < images.length; j++) {
                        if (j != ki) {
                            kimages[kimages.length] = images[j];
                        }
                    }
                    $("#" + imgId).val(kimages.join());
                    plu_show_thumbs(imgId);
                    return false;
                });
            }
        }
        if (images.length > 1) {
            thumbsC.sortable({
                update: function(event, ui) {
                    var kimages = [];
                    thumbsC.find("img").each(function() {
                        kimages[kimages.length] = $(this).attr("src");
                        $("#" + imgId).val(kimages.join());
                        plu_show_thumbs(imgId);
                    });
                }
            });
            thumbsC.disableSelection();
        }
    }

here added myplupload.css
    .filelist {
        width: 60%;
    }
    .filelist .file {
        padding: 5px;
        background: #ececec;
        border: solid 1px #ccc;
        margin-bottom: 4px;
    }
    .filelist .fileprogress {
        width: 0%;
        background: #B7C53D;
        height: 5px;
    }
    .plupload-thumbs {
    
    }
    .plupload-thumbs .thumb {
        width: 50px;
        padding-right: 5px;
        float: left;
    }
    .plupload-thumbs .thumb img {
        width: 50px;
        height: 50px;
    }
    .ui-sortable  .thumb img {
        cursor: pointer;
    }


if you want download code please click here


Tuesday 16 February 2016

image upload with compress image and add text into image in using php

Hello Here Example Image compress and add text into image

<?php
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);
 // Set Path to Font File
$color = imagecolorallocate($image, 255, 255, 255);

//x-coordinate of the upper left corner.
$xPos = 600;
//y-coordinate of the upper left corner.
$yPos = 200;

//Writting the picture
imagestring($image,5,$xPos,$yPos,"Add Your Text Here",$color);
imagejpeg($image, $destination_url, $quality);



return  $destination_url;
}
if(isset($_POST['submit'])){
$tempPath = $_FILES['upload']['tmp_name'];
$mypath = "compress";
if(!is_dir($mypath)){
mkdir($mypath);
}
 $filename = $_FILES['upload']['name'];
 $destination = $mypath."/".$filename;

$destination  =   compress_image($tempPath,$destination,90);
}
?>

<form method="post" enctype="multipart/form-data">

<input type="file" name="upload"/>
<input type="submit" name="submit" value="upload"/>

</form>

Saturday 30 January 2016

Insert Csv File Data in Mysql using Php with Validation

Insert Csv File Data in Mysql using Php with Validation  Full Example

Sample Csv File Test.csv

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>

<script type="application/javascript">
$(document).ready(function(e) {
    $('#pincodeList').validate({
        rules: {
            Csv: {
                required: true,
extension: "xls|csv"
              
            }

        },

    messages: {
        Csv: {
            extension: 'Please upload a csv file!'
        }
}

    });
});
</script>

<?php
include('connect.php');


if($_POST['submit']){
$csv_file = $_FILES['Csv']['name'];
$tmpFilePath =$_FILES['Csv']['tmp_name'];
$newFilePath="pincodeUpload/";
$mypath = "pincodeUpload/".$csv_file;
move_uploaded_file($tmpFilePath, $mypath);
if ( ! is_dir($newFilePath)) {

mkdir($newFilePath);

$csv_file =$mypath;

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];
        }

    $col1 = $col[0];

  
// SQL Query to insert data into DataBase
$query = "INSERT INTO pincode(Pincode) VALUES('$col1')";
$s     = mysql_query($query);
 }
    fclose($handle);
}

}

?>

<form id="pincodeList" name="pincodeList" method="post" enctype="multipart/form-data">
               <div class="row">
               <div class="co-md-3 col-sm-6">
<input  type="file" name="Csv" >
                </div>
                <div class="co-md-3 col-sm-6">
<input class="btn btn-success" type="submit" name="submit" value="Upload Csv"/>
                </div>
                </div>
</form>

Wednesday 20 January 2016

Upload Multiple-image Using Webservice in PHP



Hello
Upload Multiple-image Using Webservice in PHP

<?php



 
  if(isset($_POST['submit'])){
 
 
for($i=0; $i<count($_FILES['upload']['name']); $i++) {

/** valiation  only 1 Mb File Upload **/
if($_FILES['upload']['size'][$i] > 1048576){
$notice_image = '<div class="alert alert-info fade in">
    <a title="close" aria-label="close" data-dismiss="alert" class="close" href="#">×</a>
    <strong>Info!</strong> Image Size Must Be Less Than 1 Mb. Your Image is "'.$_FILES['upload']['name'][$i].'"
</div>';

}else{

$tmpFilePath =$_FILES['upload']['tmp_name'][$i];


//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "ProductImg/";

if ( ! is_dir($newFilePath)) {

mkdir($newFilePath);


$picture =uniqid()."_".$_FILES['upload']['name'][$i];
$mypath = "ProductImg/".$picture;
//Upload the file into the temp dir
// if(move_uploaded_file($tmpFilePath, $mypath)) {
if(!file_exists($mypath)){
//move_uploaded_file($tmpFilePath, $mypath);
/** remove Comment when not use webservice*/

 
 
if(!empty($picture))
  {

 
$data = base64_decode($_FILES['upload']['name'][$i]);
$file = fopen($mypath, "w");
fwrite($file,$data);
fclose($file);
  }


}

}


}
}

}
?>

<form method="post" enctype="multipart/form-data">
<?php echo $notice_image; ?>
<input type="file" name="upload[]" multiple="multiple" >
<input type="submit" name="submit" value="save">

</form>

Monday 18 January 2016

Get longitude and latitude using address with php

Get longitude and latitude using address with php 

here The Example For that.

function Get_LatLng_From_Google_Maps($address) {
    $address = urlencode($address);

    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";

    // Make the HTTP request
    $data = @file_get_contents($url);
    // Parse the json response
    $jsondata = json_decode($data,true);

    // If the json data is invalid, return empty array
    if (!check_status($jsondata))   return array();

    $LatLng = array(
        'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
        'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
    );

    return $LatLng;
}

/*
* Check if the json data from Google Geo is valid
*/

function check_status($jsondata) {
    if ($jsondata["status"] == "OK") return true;
    return false;
}

/*
*  Print an array
*/

function d($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}
$address="bhavnagar,gujrat,india";
$arry_lat_lag = Get_LatLng_From_Google_Maps($address);

Monday 28 December 2015

Get near by Location using latitude and longitude from php and mysql in google map Kilometer

Get near by Location using latitude and longitude from php and mysql in google map Kilometer

To search by miles  instead of kilometers, replace 6371 with .3959

<?php


$username="root";
$password="";
$database="googlemap";



// Get parameters from URL
$center_lat = 23.036730;
$center_lng = 72.516373;
$radius = 6;


$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}

// Search the rows in the mstuser table
$query = sprintf("SELECT usermail, res_name, lat, lng, ( 6371  * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM mstuser HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",


  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));

  /*$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20",


  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));*/
$result = mysql_query($query);

$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}

header("Content-type: application/json");
$i=0;
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){


  $data[$i]['usermail'] = $row['usermail'];
  $data[$i]['res_name'] = $row['res_name'];
  $data[$i]['lng'] = $row['lng'];
  $data[$i]['lat'] = $row['lat'];
  $data[$i]['distance'] = $row['distance'];

  $i++;

}

echo json_encode($data);
?>

Sunday 6 December 2015

Split String with comma Loop in Mysql store Proceture Example

Hello

Here Very Usefull for Split String with comma Loop in Mysql store Proceture Example

Split String with comma Loop in Mysql store proceture
this fully example how to use

Loop In Mysql

and split string in mysql

begin
  
   
   
    SET @InitCounter := 1;
      SET @Param := "11,22,33,44,";
    
 
  
  
      
    myLoop: loop 
   
 SET @NextCounter := LOCATE(',',@Param);

 SET @SUBSTR := SUBSTRING(@Param,@InitCounter,@NextCounter);

 SET @Param := REPLACE(@Param,@SUBSTR,'');

 SET @SUBSTR:= REPLACE(@SUBSTR,',','');

 SET @ParamLength := LENGTH (@Param);


 SELECT @SUBSTR;




                      
        if  
       
             @ParamLength = 0
        then
            leave myLoop;             
        end if;
       
    end loop myLoop;                   
   
END

Monday 16 November 2015

how to remove index and unique constraint in mysql

Hello

here Example of remove how to remove index and unique constraint in mysql

first check table how many constraint  in table after you can remove.

here the query for show index in table

SHOW INDEX FROM Your-table-Name

after remove all index name display in column

here the query

ALTER TABLE Your-table-Name DROP INDEX Your-field-unique-constraint -name;

Please check this 

Login With Facebook Using javascript SDK Example

Hello

Here Example of Facebook Login With Javascript SDK
the login flow step-by-step and explain each step clearly - this will help you if you are trying to integrate Facebook Login into an existing login system, or just to integrate it with any server-side code you're running. But before we do that, it's worth showing how little code is required to implement login in a web application using the JavaScript SDK.

Create Login.php File

Code For Login.php

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function facebook_login (){
    if(typeof(FB) == "undefined") {
        alert("Facebook SDK not yet loaded please wait.")
      }
    FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        console.log('Logged in.');
        basicAPIRequest();

      }
      else {
       FB.login(function(response) {
 
      if (response.status === 'connected') {
        console.log('Logged in.');
        basicAPIRequest();
  }
 
}, {scope: 'email,user_birthday,user_location,public_profile,publish_actions'});

      }
    });    
}

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'your-app-id',
      xfbml      : true,
   status     : true, // check login status
      version    : 'v2.0'
    });

FB.Event.subscribe('auth.login', function () {
         basicAPIRequest()
      });

  };

 
  

  
  
   (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));


function basicAPIRequest() {
    FB.api('/me',
        {fields: "id,about,age_range,picture,bio,birthday,context,email,first_name,gender,hometown,link,location,middle_name,name,timezone,website,work"},
        function(response) {
         console.log('API response', response);
         /*  $("#fb-profile-picture").append('<img src="' + response.picture.data.url + '"> ');
          $("#name").append(response.name);
          $("#user-id").append(response.id);
          $("#work").append(response.gender);
          $("#birthday").append(response.birthday);
          $("#education").append(response.hometown);
  $("#email").append(response.email);*/
 

 
  $.ajax({
  url: "facebook_login_query.php",
  data: {
  email:response.email,
  birthday : response.birthday,
  gender : response.gender
  },
  success: function( response ) {
alert(response);
window.location.href = "http://localhost/home.php";
return false;
 
  }
 

});
 
        }
    );
  }



</script>
<!--<div  class="fb-login-button" data-scope="email,user_birthday,user_hometown,user_location,user_website,user_work_history,user_about_me
" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="true"  >
</div>
</div> -->


<button id='load' onClick="facebook_login();">Load data</button>
</html>

Create facebook_login_query.php

<?php
include('connect.php');
session_start();


 echo $uname = $_GET['email'];


if(!is_null){
echo $newbirthday = $_GET['birthday'];
echo $birthday = date("Y-m-d", strtotime($newbirthday));

}else{
$birthday= '';
}
echo $gender = strtolower($_GET['gender']);



   $select="select * from mstuser where username='$uname' and facebook_login='1' and  isActive = '1' AND isDelete = '0'";
$result=mysql_query($select);

  $total_result = mysql_num_rows($result);
if($total_result == 1){

$row = mysql_fetch_assoc($result);
  $_SESSION['vid']=$row['id'];
$_SESSION['username'] = $row['username'];
  $roleid = $row['roleid'];
$count=mysql_num_rows($result);


}else{
echo "insert into mstuser set username='$uname',facebook_login='1',isActive = '1',isDelete = '0' ";
  $insert_mstuser = mysql_query("insert into mstuser set username='$uname',facebook_login='1',isActive = '1',isDelete = '0' ");



  $select="select * from mstuser where username='$uname' and facebook_login='1' and  isActive = '1' AND isDelete = '0'";
$result=mysql_query($select);
$row = mysql_fetch_assoc($result);
  $_SESSION['vid']=$row['id'];
  $roleid = $row['roleid'];
$_SESSION['username'] = $row['username'];
$count=mysql_num_rows($result);



}
?>

Create Home.php

echo "Welcome user";

Tuesday 3 November 2015

Get Country State and City using JavaScript ajax and php

Hello

Here Example Of set your country,state,city using javascript ajax and php

Country State City Dropdown Using Ajax. ... In the onChage event of the country drop down we have called showhint() function of the javascript and also get current state of city using show_city();

Full Code

--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `id` int(11) NOT NULL auto_increment,
  `cid` int(11) NOT NULL,
  `sid` int(11) NOT NULL,
  `city_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`id`, `cid`, `sid`, `city_name`) VALUES
(1, 1, 1, 'ahmedabad'),
(2, 1, 1, 'rajkot'),
(3, 2, 3, 'afarica city 1'),
(4, 2, 4, 'afarica city 2');

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

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `id` int(11) NOT NULL auto_increment,
  `countryname` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`id`, `countryname`) VALUES
(1, 'india'),
(2, 'africa');

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

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `id` int(11) NOT NULL auto_increment,
  `cid` int(11) NOT NULL,
  `s_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`id`, `cid`, `s_name`) VALUES
(1, 1, 'gujrat'),
(2, 1, 'bihar'),
(3, 2, 'afarica state1'),
(4, 2, 'afarica state 2');

all_date.php file

<script>
function showHint(str) {

    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {


                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "getstate.php?q=" + str, true);
        xmlhttp.send();
    }

}

function showCity(str) {


    if (str.length == 0) {
        document.getElementById("txtCity").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {


                document.getElementById("txtCity").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "getcity.php?q=" + str, true);
        xmlhttp.send();
    }

}

</script>

<?php

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

mysql_select_db('test_country');

$get_country = mysql_query("select * from country");



?>
<label> country</label>

<select name="country" onchange="showHint(this.value)" >
<option value="0" >select country</option>
<?php
while($row_country = mysql_fetch_assoc($get_country)){ ?>


<option value="<?php echo $row_country['id']; ?>"/>
<?php echo $row_country['countryname'];  ?>
</option>


<?php
}
?>
</select>
<select name="state" id="txtHint" onchange="showCity(this.value)" >
</select>

<select name="city" id="txtCity">
</select>
</br>

getstate.php file

<option value="0" >select state</option>
<?php
mysql_connect("localhost","root","");

mysql_select_db('test_country');

$q=$_GET['q'];

echo $select_state= mysql_query("select * from state where cid=".$q);

while($result_state= mysql_fetch_array($select_state)){ ?>

<option value="<?php echo $result_state['id']; ?>"><?php echo $result_state['s_name']; ?></option>

<?php }
?>

getcity.php file

<option value="0" >select City</option>
<?php
mysql_connect("localhost","root","");

mysql_select_db('test_country');

$q=$_GET['q'];

echo $select_state= mysql_query("select * from city where sid=".$q);

while($result_state= mysql_fetch_array($select_state)){ ?>

<option value="<?php echo $result_state['id']; ?>"><?php echo $result_state['city_name']; ?></option>

<?php }
?>

Monday 2 November 2015

How to Get Difference Between Two date in php

Hello,

Here Example of get difference between two dates in year,month and days.

You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods.

<?php

$date1 = "2014-03-24";
$date2 = "2015-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$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));




echo "Get Your Year diffrernce:-".$years."year";
echo "<br/>";
echo "Get Your Year diffrernce:-".$months."months";
echo "<br/>";
echo "Get Your Year diffrernce:-".$days."days";

Monday 28 September 2015

include , require and require_once , include_once in php

 include , require and require_once , include_once in php 


include, require and require_once,include_once are used to include a file into the PHP code

for example of include and require

<h1>Welcome to My blog!</h1>
<?php include 'header.php';
?>

it can added file in php code.

in require example

<h1>Welcome to My blog!</h1>
<?php require 'header.php';
?>

difference between  include and require

 when a file is included with the include statement and PHP cannot find it, the script will continue to execute

and

the echo statement will not be executed because the script execution dies after the require statement returned a fatal error

include_once 

It can be used include a PHP file another one, it can used to add files once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

Syntax



include_once('name of the called file with path');

example 

<?php include_once('xyz.php'); 

?>

same as require_once used.

<?php require_once('example.php')  ?>

include_once and require_once same different with include and require.




Difference between Echo And Print In Php

Hello,

Here I can Give both of use echo and print in php. I give example and use.

Echo and Print are almost same. they are both output on screen. they are used with and without
parentheses.

Difference Echo And Print



  1. print return value and echo not return value.
  2. echo faster than print.
  3.  echo without parentheses can take multiple parameters, which get concatenated but print give error.

How Can Use.



$data = "hello".
$data1 ="jaydip";

echo "<h2>My echo information</h2>";
echo "namste !<br>";

echo $data."".$data1;


echo without parentheses can take multiple parameters 
echo "jj","123",1,3;

same like in Print:

$data = "hello".
$data1 ="jaydip";

print "<h2>My echo information</h2>";
print "namste !<br>";

print $data."".$data1;

you can use as print in 
$test=1;
($test==2) ? print "true" : print "false";


Friday 28 August 2015

Use Ternary Operator in Php

Hello

I am Here Create Some Example How to use Ternary operator in php.

Ternary Operator use as simple if and else condition

$bool_val = 5;

echo ($bool_val <= 5) ? 'true' : 'false';.

it result is true.

if $bool_val = 6. then out put will be different. it false.

before ? it's like if condition  and : else condition.

For Check this

<?php
$age = 18;
    $agestr = ($age < 18) ? 'child' : 'adult';

it same like this

<?php
      if ($age < 16) {
        $agestr = 'child';
    } else {
        $agestr = 'adult';
    }
 

?>

here

another example


        $valid = false;
    $lang = 'french';
    $x = $valid ? ($lang === 'french' ? 'oui' : 'yes') : ($lang === 'french' ? 'non' : 'no');
 
    echo $x;

like this

if($valid){
   
    if($lang === 'french')
    {
        $x='oui';
    }else{
        $x = 'yes';
    }
} else{
   
      if($lang === 'french')
    {
        $x='non';
    }else{
        $x = 'no';
    }
   
}
echo $x;




Tuesday 9 June 2015

Implode And Explode Function In Php

Hello All,

Here I Want give example of how to use implode and explode in php.

Use of Implode 


=> The implode() function returns a string from the elements of an array. separator parameter of implode() is optional.

I give example for it.


$array = array("hello","all","be","happy","always");

$result =  implode($array);

echo $result;

it result will be => helloallbehappyalways.

if you can separate array using space then you can write this way

 $result =  implode(" ",$array);

this result will me => hello all be happy always

you can any of parameter to separate array;

like i give emaple for it


echo $result =  implode("$",$array)."<br/>";
echo $result =  implode("+",$array)."<br/>";
echo $result =  implode("-",$array)."<br/>";
echo  $result =  implode("*",$array)."<br/>";

this result will me =>

hello$all$be$happy$always
hello+all+be+happy+always
hello-all-be-happy-always
hello*all*be*happy*always

I think yon can understand what implode work it can make string of array using separate
by it parameter.you can use different parameter that can separate it. 

Use of Explode

=> this function use of breaks a string into an array.separator parameter cannot be empty string.

i will give example for it.

$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry";
$result = explode(" ",$string);
print_r($result);

this result will be=>
Array ( [0] => Lorem [1] => Ipsum [2] => is [3] => simply [4] => dummy [5] => text [6] => of [7] => the [8] => printing [9] => and [10] => typesetting [11] => industry )

if you want to separate to this different word.

if you to get separate word then check below code

echo "<br/>";
 $count = count($result);
 
 for($i=1;$i<=$count;$i++){
    
    $line =  each($result);
    print_r($line);
    echo "<br/>";
    echo $line['value']."<br/>";
 }

this out put will be
=>
Lorem
Array ( [1] => Ipsum [value] => Ipsum [0] => 1 [key] => 1 )
Ipsum
Array ( [1] => is [value] => is [0] => 2 [key] => 2 )
is
Array ( [1] => simply [value] => simply [0] => 3 [key] => 3 )
simply
Array ( [1] => dummy [value] => dummy [0] => 4 [key] => 4 )
dummy
Array ( [1] => text [value] => text [0] => 5 [key] => 5 )
text
Array ( [1] => of [value] => of [0] => 6 [key] => 6 )
of
Array ( [1] => the [value] => the [0] => 7 [key] => 7 )
the
Array ( [1] => printing [value] => printing [0] => 8 [key] => 8 )
printing
Array ( [1] => and [value] => and [0] => 9 [key] => 9 )
and
Array ( [1] => typesetting [value] => typesetting [0] => 10 [key] => 10 )
typesetting
Array ( [1] => industry [value] => industry [0] => 11 [key] => 11 )
industry

if you want to get only word echo $line['value]; use it and print_r($line); comment it.

you can also limit parameter to return a number of array elements

check this example

$string = "Lorem,Ipsum,is,simply,dummy,text,of,the,printing,and,typesetting,industry";

if you want to only 1 key then code this

print_r(explode(',',$string,0));

this result will =>
Array ( [0] => Lorem,Ipsum,is,simply,dummy,text,of,the,printing,and,typesetting,industry )

if you want 2 key then

print_r(explode(',',$string,2));

this result will=>
Array ( [0] => Lorem [1] => Ipsum,is,simply,dummy,text,of,the,printing,and,typesetting,industry )

if you want all key then you can use this code

print_r(explode(',',$string,-1));


this result will be =>

Array ( [0] => Lorem [1] => Ipsum [2] => is [3] => simply [4] => dummy [5] => text [6] => of [7] => the [8] => printing [9] => and [10] => typesetting )

this use of explode and implode. explode use for string to array and implode use for array to string.

 



 

Email Already Exit Using Jquery And Php

Hello All,

I am Simple Learn How to check email already exit. I am create code and check if

email already exit then you cannot submit  and also also validation of email.

I am give the code for that you can check it and use it.

you have to create to file

1)email.php
2)check.php

in your email.php wriite this code

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 
   $("#myform").submit(function(){
 
       if(!emailok)
       {
        alert('check your email');
        return false;
       }
   
    });
$('#email').blur(function(){
   alert($('#email').val());
    $.ajax({
        type:"post",
        data:"email="+$('#email').val(),
        url:"check.php",
        beforeSend:function(){
            $("#email_info").html("checking email...");
        },
        success:function(data){
         
            if(data == "invalid"){
                $("#email_info").html("check your Email");
           
       
            emailok = false;
            }else if(data !="0"){
                  $("#email_info").html("email already exit");
             
            }else{
            emailok = true;
            $("#email_info").html("email ok");
            }
         
         
        }
     
     
     
    });
 
    });
});
</script>
<form id="myform" method="post">
<input type="text" id="email" name="email"/>
<input type="submit" />
</form>
<div id="email_info"></div>


second file is check.php

add this code

<?php
 $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   if(! $conn )
   {
     die('Could not connect: ' . mysql_error());
   }

 
   mysql_select_db('blog',$conn);
 
   $email = $_POST['email'];
 
   if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
 
   $sql =  mysql_query('select email from email where email="'.$email.'"' );
 
   $result = mysql_fetch_array($sql);
 
 
 
    echo $num = mysql_num_rows($sql);
 }else{
 
    echo "invalid";
 }
 
 
 
 
 
 
   mysql_close($conn);
?>

table code

--
-- Table structure for table `email`
--

CREATE TABLE IF NOT EXISTS `email` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `email`
--

INSERT INTO `email` (`id`, `email`, `password`) VALUES
(1, 'test@gmail.com', 'test'),
(2, 'teset@gmail.com', 'test');