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

Wednesday 27 December 2017

link preview like facebook using php

link preview like facebook using php



Hello here example with text area 

<?php

$string =  "adasd asdad asdasd https://www.facebook.com asdasd asdasdsa ";

$preview_data = array();
$preview_data['title'] = "";
$preview_data['desc'] = "";
$preview_data['url'] = "";
$preview_data['image'] = "";

$myurl = "";
if($string!=''){
$string_array = explode(" ",$string);
if(count($string_array) > 0){
foreach($string_array as $string_value){
if (filter_var($string_value, FILTER_VALIDATE_URL)) {
$myurl = $string_value;
break;
} // if of url
if($string_value!=''){
$sub_string_check = explode(".",$string_value);
if(count($sub_string_check) >= 2){
$myurl = "http://" .$string_value;
break;
}
}
} // foreach for loop
 
} // if for array count
}// main if condition


if (filter_var($myurl, FILTER_VALIDATE_URL)) {
$agent = "'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';";
$ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_URL, $myurl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    
    $data = curl_exec($ch);
    curl_close($ch);
$dom = new DOMDocument();
@$dom->loadHTML($data);
//$page = new self();
    
    // Parse DOM to get Title
    $nodes = $dom->getElementsByTagName('title');
    $title = $nodes->item(0)->nodeValue;
    
    // Parse DOM to get Meta Description
    $metas = $dom->getElementsByTagName('meta');
    $body = "";
    for ($i = 0; $i < $metas->length; $i++) {
        $meta = $metas->item($i);
$name = $meta->getAttribute('property');
$name123 = $meta->getAttribute('name');
        //if ($meta->getAttribute('name') == 'description') {
             $body[$name] = $meta->getAttribute('content');
$body[$name123] = $meta->getAttribute('content');
        //}
    }
    
    // Parse DOM to get Images
    $image_urls = array();
$image_src = array();
    $images = $dom->getElementsByTagName('img');
     
     for ($i = 0; $i < $images->length; $i ++) {
         $image = $images->item($i);
         $src = $image->getAttribute('src');
         
         if(filter_var($src, FILTER_VALIDATE_URL)) {
             $image_src[] = $src;
         }
     }
    
    $output = array(
        'title' => $title,
        'image_src' => $image_src,
        'body' => $body
    );
echo "<pre>";
print_r($output);
$title = "";
$description ="";
$url = "";
$image_url = "";
if(isset($output['title'])){
$title = $output['title'];
}elseif(isset($output['body']['og:title'])){
$title = $output['body']['og:title'];
}elseif(isset($output['body']['twitter:title'])){
$title = $output['body']['twitter:title'];
}
if(isset($output['body']['description'])){
$description = $output['body']['description'];
}elseif(isset($output['body']['og:description'])){
$description = $output['body']['og:description'];
}elseif(isset($output['body']['twitter:description'])){
$description = $output['body']['twitter:description'];
}
if(isset($output['body']['url'])){
$url = $output['url'];
}elseif(isset($output['body']['og:url'])){
$url = $output['body']['og:url'];
}elseif(isset($output['body']['twitter:url'])){
$url = $output['body']['twitter:url'];
}elseif(isset($output['body']['al:web:url'])){
$url = $output['body']['al:web:url'];
}else{
$url =$myurl;
}
if(isset($output['body']['image'])){
$image_url = $output['image'];
}elseif(isset($output['body']['og:image'])){
$image_url = $output['body']['og:image'];
}elseif(isset($output['body']['twitter:image'])){
$image_url = $output['body']['twitter:image'];
}elseif(isset($output['image_src'][0])){
$image_url = $output['image_src'][0];
}
$preview_data['title'] = $title;
$preview_data['desc'] = $description;
$preview_data['url'] = $url;
if($image_url!=""){
$preview_data['image'] = filter_var($image_url, FILTER_VALIDATE_URL)?$image_url:$url.$image_url;
}
 
 
/*if(!filter_var($image_url, FILTER_VALIDATE_URL)) {
             
foreach($output['body'] as $t){
$preview_data['image'] = $url.$t;
}
 
         }*/
}
echo "<pre>";
print_r($preview_data);

?>

Friday 17 November 2017

Converting Timestamp to time ago in PHP e.g 1 day ago, 1 year ago

Converting Timestamp to time ago in PHP e.g 1 day ago, 1 year ago

 

Hello Here Example of set up time as human readable formate in php

<?php
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
echo date('Y-m-d H:i:s');
echo "<br/>";
echo time_elapsed_string('2017-11-17 11:36:00',true);
echo "<br/>";
echo time_elapsed_string('@1367367755'); # timestamp input
echo "<br/>";
echo time_elapsed_string('2013-05-01 00:22:35', true);
echo "<br/>";
?>



Thursday 26 October 2017

PHP multidimensional array search by value and get array value

PHP multidimensional array search by value and get array value 

Hell here exmple of array search in multidinsional
see the array you can get array key of multidensional and get value using array

check this out put

Array
(
    [0] => Array
        (
            [typeid] => 1
            [typename] => Enveloppe
            [max_kg] => 0.30
            [isactive] => 1
            [isdelete] => 0
        )

    [1] => Array
        (
            [typeid] => 2
            [typename] => Documents
            [max_kg] => 2.00
            [isactive] => 1
            [isdelete] => 0
        )

    [2] => Array
        (
            [typeid] => 3
            [typename] => Colis
            [max_kg] => 300.00
            [isactive] => 1
            [isdelete] => 0
        )

)
 
$new_type_id = array_combine(array_keys($get_row_msttype), array_column($get_row_msttype, 'typename'));
      $search_typeid = array_search('Enveloppe', $new_type_id);
      
      if(is_int($search_typeid)){
       $typeid =  $get_row_msttype[$search_typeid]['typeid']; // you can get value using array value here
      }else{
       $typeid = '';
      }
      
      echo $typeid; 

Tuesday 24 October 2017

Google Translate using javascript english to french without select value from dropdown on page load



Google Translate using javascript english to french without select value from dropdown on page load

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>

<style>
#google_translate_element{width:300px;float:right;text-align:right;display:block}
.goog-te-banner-frame.skiptranslate { display: none !important;}
body { top: 0px !important; }
#goog-gt-tt{display: none !important; top: 0px !important; }
.goog-tooltip skiptranslate{display: none !important; top: 0px !important; }
.activity-root { display: hide !important;}
.status-message { display: hide !important;}
.started-activity-container { display: hide !important;}
#google_translate_element{ display: none !important;}
</style>
<div id="google_translate_element"></div>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({ 
    
  includedLanguages: 'fr',
      layout: google.translate.TranslateElement.InlineLayout.SIMPLE
    }, 'google_translate_element');

var lang = 'French';
var $frame = $('.goog-te-menu-frame:first');
console.log($frame.contents().find('.goog-te-menu2-item span.text:contains('+lang+')').click());

  }
</script>








Why do we use it?

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Tuesday 8 August 2017

File upload show progress bar ajax without formdata and php

File upload show progress bar ajax without formdata and php

ajax file



 <script
  src="http://code.jquery.com/jquery-1.12.4.js"
  integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU="
  crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

  
             
              <script type="application/javascript">
      $(document).on("change", "#myfile", function() {
 
  var ext = this.value.match(/\.([^\.]+)$/)[1];
  var array_ext = ['zip','pdf','jpg', 'png', 'gif', 'bmp', 'jpeg', 'GIF', 'JPG', 'PNG', 'doc', 'txt', 'docx', 'pdf', 'xls', 'xlsx','zip'];
  if(jQuery.inArray( ext, array_ext ) !== -1){


    var file_data = $("#myfile").prop("files")[0];   // Getting the properties of file from file field
    var form_data = new FormData();                  // Creating object of FormData class
    form_data.append("myfile", file_data)              // Appending parameter named file with properties of file_field to form_data
    //form_data.append("user_id", 123)                 // Adding extra parameters to form_data
    $.ajax({
                    url: "upload_avatar.php",
                  //  dataType: 'script',
xhr: function () {
                            var xhr = new window.XMLHttpRequest();
                            xhr.upload.addEventListener("progress", function (evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = evt.loaded / evt.total;
                                    percentComplete = parseInt(percentComplete * 100);
                                    $('.myprogress').text(percentComplete + '%');
                                    $('.myprogress').css('width', percentComplete + '%');
                                }
                            }, false);
console.log(xhr);
                            return xhr;
                        },
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: form_data,                         // Setting the data attribute of ajax with file_data
                    type: 'post',
success: function(res){
//alert(res);
  // $('.myprogress').text(0 + '%');
                            //        $('.myprogress').css('width', 0 + '%');
}
           })
  
  }else{
   alert('Not valid file');
  $("#myfile").val('');
  return false;
}
    })

  </script>
    <input id="myfile" type="file" name="myfile" />
    <input type="hidden" value="" name="image_file_path">
    <!--<button id="upload" value="Upload" >Upload</button>-->
     <div class="form-group">
                        <div class="progress">
                            <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                        </div>

                        <div class="msg"></div>
                    </div>
   
    upload_avatar.php

 
<?php

error_reporting(0);
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {

    $path = "uploads/"; //set your folder path
if(!is_dir($path)){
mkdir($path,0777,true);
}
    //set the valid file extensions
    $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "GIF", "JPG", "PNG", "doc", "txt", "docx", "pdf", "xls", "xlsx","zip"); //add the formats you want to upload

    $name = $_FILES['myfile']['name']; //get the name of the file
   
    $size = $_FILES['myfile']['size']; //get the size of the file
//$name= uniqid()."test";
    if (strlen($name)) { //check if the file is selected or cancelled after pressing the browse button.
        list($txt, $ext) = explode(".", $name); //extract the name and extension of the file
        if (in_array($ext, $valid_formats)) { //if the file is valid go on.
           // if ($size < 2098888) { // check if the file size is more than 2 mb
                $file_name = uniqid()."test"; //get the file name
                $tmp = $_FILES['myfile']['tmp_name'];
                if (move_uploaded_file($tmp, $path . $file_name.'.'.$ext)) { //check if it the file move successfully.


                //    echo "File uploaded successfully!!";
                } else {
                    echo "failed";
                }
          //  } else {
              //  echo "File size max 2 MB";
            //}
        } else {
            echo "Invalid file format..";
        }
    } else {
        echo "Please select a file..!";
    }
$data['message'] = "asdads";
echo json_encode($data);
    exit;
}   

Monday 7 August 2017

Quick image upload using php web service for android and ios

Quick image upload using php web service for android and ios


quick image upload using php web service for android and ios example


<?php



$path="aa/";// Set your path to image upload
if(!is_dir($path)){
mkdir($path);
}
$roomPhotoList = $_POST['image'];
$random_digit=date('Y_m_d_h_i_s');
$filename=$random_digit.'.jpg';
$decoded=base64_decode($roomPhotoList);
file_put_contents($path.$filename,$decoded);

?>

Friday 4 August 2017

Creating a thumbnail from an uploaded image using php

Creating a thumbnail from an uploaded image using php


<?php

function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
    $imgsize = getimagesize($source_file);
    $width = $imgsize[0];
    $height = $imgsize[1];
    $mime = $imgsize['mime'];

    switch($mime){
        case 'image/gif':
            $image_create = "imagecreatefromgif";
            $image = "imagegif";
            break;

        case 'image/png':
            $image_create = "imagecreatefrompng";
            $image = "imagepng";
            $quality = 100;
            break;

        case 'image/jpeg':
            $image_create = "imagecreatefromjpeg";
            $image = "imagejpeg";
            $quality = 100;
            break;

        default:
            return false;
            break;
    }
    
    $dst_img = imagecreatetruecolor($max_width, $max_height);
    $src_img = $image_create($source_file);
    
    $width_new = $height * $max_width / $max_height;
    $height_new = $width * $max_height / $max_width;
    //if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
    if($width_new > $width){
        //cut point by height
        $h_point = (($height - $height_new) / 2);
        //copy image
       // imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
    }else{
        //cut point by width

        $w_point = (($width - $width_new) / 2);
  
       // imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
    }
    
    imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $max_width, $max_height, $width, $height);
    $image($dst_img, $dst_dir);


    if($dst_img)imagedestroy($dst_img);
    if($src_img)imagedestroy($src_img);

$imagedata =ob_end_clean();
return $dst_dir;

}

$img = $_FILES['file']['tmp_name'];
  $file_name = "aaa/"."thumb_".$_FILES['file']['name'];
resize_crop_image(250, 250,$img, $file_name);

?>

<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="save" value="save"/>

</form>

Check all with datatables pagination

Check all with datatables pagination

Here example of   Check all with datatables pagination
<body>
<script
  src="http://code.jquery.com/jquery-1.12.4.js"
  integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU="
  crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script type="application/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="application/javascript">
$(document).ready(function(e) {
   
var oTable = $('#seller_table').DataTable({"bSort":false, responsive: true});

   // var allPages = oTable.cells( ).nodes( ); // Remove comment if you want select all datatable value

    $('body').on("click","#selectAll",function () {
alert();
        if ($(this).hasClass('allChecked')) {
            $('#seller_table').find('input[type="checkbox"]').prop('checked', false);
//$(allPages).find('input[type="checkbox"]').prop('checked', false); // Remove comment if you want select all datatable value
        } else {
            $('#seller_table').find('input[type="checkbox"]').prop('checked', true);
//$(allPages).find('input[type="checkbox"]').prop('checked', true); // Remove comment if you want select all datatable value
        }
        $(this).toggleClass('allChecked');
    })

$("#delete_new_area").click(function(){
var check_all = [];
$(".new_area_value").each(function(index, element) {
           
if(this.checked){
check_all.push($(this).val());
}
        });


if(check_all.length>0){

// here your code for check value;
}
});

$('#seller_table').on('page.dt', function () {

     $('#selectAll').toggleClass('allChecked');
$('#seller_table').find('input[type="checkbox"]').prop('checked', false);
} );

});



</script>
<table id="seller_table" class="table responsive  table-striped table-bordered dataTable no-footer" role="grid" aria-describedby="seller_table_info">
  <thead>
    <tr role="row">
      <th class="sorting_disabled" rowspan="1" colspan="1" style="width: 130px;"> <button type="button" id="selectAll" class="main btn btn-primary "> <span class="sub"></span> Select </button></th>
      <th class="sorting_disabled" rowspan="1" colspan="1" style="width: 280px;">Email</th>
      <th class="sorting_disabled" rowspan="1" colspan="1" style="width: 608px;">Area</th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td><input class="new_area_value" value="4" type="checkbox"></td>
      <td>myinformation@gmail.com</td>
      <td>11416 NE 91ST ST </td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="5" type="checkbox"></td>
      <td>myinformation@gmail.com</td>
      <td>11416 NE 91ST ST </td>
    </tr>
    <tr role="row" class="odd">
      <td><input class="new_area_value" value="6" type="checkbox"></td>
      <td>myinformation@gmail.com</td>
      <td>11416 NE 91ST ST </td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="9" type="checkbox"></td>
      <td>myinformation@gmail.com</td>
      <td>Asheville%2C+NC%2C+United+States</td>
    </tr>
    <tr role="row" class="odd">
      <td><input class="new_area_value" value="10" type="checkbox"></td>
      <td>test@yopmail.com</td>
      <td>Ashburn, VA, United States</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="14" type="checkbox"></td>
      <td>-NA-</td>
      <td>Los Angeles, CA, United States</td>
    </tr>
    <tr role="row" class="odd">
      <td><input class="new_area_value" value="16" type="checkbox"></td>
      <td>-NA-</td>
      <td>Lower Parel, Mumbai, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="17" type="checkbox"></td>
      <td>myinformation@gmail.com</td>
      <td>Lower Parel, Mumbai, Maharashtra, India</td>
    </tr>
    <tr role="row" class="odd">
      <td><input class="new_area_value" value="20" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test Area, Yerawada, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
    <tr role="row" class="even">
      <td><input class="new_area_value" value="21" type="checkbox"></td>
      <td>-NA-</td>
      <td>Test, Janta Road, Dattawadi, Pune, Maharashtra, India</td>
    </tr>
  </tbody>
</table>
</body>

Sunday 30 July 2017

create push notification for apple

create push notification for  apple



function ios_sendPushNotification($pushMessage){



$gcm_regid = "iphoneid"; // FCM ID

if($gcm_regid!=""){



$deviceToken = $gcm_regid;
    // Put your private key's passphrase here:
    $passphrase = "123";

    // Put your alert message here:
    $message = $pushMessage;

    ////////////////////////////////////////////////////////////////////////////////


try{

    $ctx = stream_context_create();

    stream_context_set_option($ctx, 'ssl', 'local_cert', 'pushcert.pem'); // Path of pem file
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

    // Open a connection to the APNS server
    $fp = stream_socket_client(
        'ssl://gateway.sandbox.push.apple.com:2195', $err,
        $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

  /*  if (!$fp)
        exit("Failed to connect: $err $errstr" . PHP_EOL);

    echo 'Connected to APNS' . PHP_EOL;*/

    // Create the payload body
    $body['aps'] = array(
        'alert' => $message,
        'sound' => 'default'
        );

    // Encode the payload as JSON
    $payload = json_encode($body);

    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));

   /* if (!$result)
    {  
        echo 'Message not delivered' . PHP_EOL;
    }
    else
    {  
        echo 'Message successfully delivered' . PHP_EOL;

    }*/

    // Close the connection to the server
    fclose($fp);
}catch(Exception  $e){
}


}





}

call funtion
ios_sendPushNotification("message")

Create custom notification in android using fcm

Create custom notification in andoid using fcm


Create custom nofication code


function sendPushNotification($pushMessage){

$gcm_regid = "define GCM ID";

if($gcm_regid != ""){


// Custom Nofification


$icon_image = "front/images/example.png";



$fields = array (
/*'notification' =>
array (
'title' => 'title',
'body' => $pushMessage,
'icon' => $icon_image,
'sound' => 'default',

//'click_action' => $main_url,
),*/
'data' => array("title"=>(string)"title",
"message"=>(string)$pushMessage,
//"is_background"=>false,
"image"=> (string)$icon_image,
"timestamp"=> (string)date("Y-m-d G:i"),

),
"to" => $gcm_regid,
);

$gcm_api_key =  "Google Api Key";


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: key=".$gcm_api_key;
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
//echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
}


}
call the function 
sendPushNotification("your push  notification")

 this example for normal push notification

function sendPushNotification($pushMessage){

$gcm_regid = "define GCM ID";

if($gcm_regid != ""){


// Custom Nofification


$icon_image = "front/images/example.png";



$fields = array (
'notification' =>
array (
'title' => 'title',
'body' => $pushMessage,
'icon' => $icon_image,
'sound' => 'default',

//'click_action' => $main_url,
),
/*'data' => array("title"=>(string)"title",
"message"=>(string)$pushMessage,
//"is_background"=>false,
"image"=> (string)$icon_image,
"timestamp"=> (string)date("Y-m-d G:i"),

),*/
"to" => $gcm_regid,
);

$gcm_api_key =  "Google Api Key";


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: key=".$gcm_api_key;
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
//echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
}



call the function 
sendPushNotification("your push  notification")

Wednesday 28 June 2017

Stripe checkout.js - passing custom params to token callback

Stripe checkout.js - passing custom params to token callback

<script src="https://checkout.stripe.com/checkout.js"></script>
<button class='pay-deposit' data-booking-id='3455'>Pay Deposit</button>
<button class='pay-deposit' data-booking-id='335'>Pay Deposit</button>
<button class='pay-deposit' data-booking-id='34'>Pay Deposit</button> 
 


 
 # JS file
$('.pay-deposit').on('click', function(event) {
  event.preventDefault();

  // Get booking information from database
  var booking_id = $(this).data('booking-id');
  $.getJSON("/bookings/"+booking_id, function(data) {

    // Open Checkout with further options
    handler = stripe_checkout(booking_id);
    handler.open({
      name: "My Bookings",
      description: data["description"],
      amount: data["amount"],
      email: data["email"],
    });

    // Close Checkout on page navigation
    $(window).on('popstate', function() {
      handler.close();
    });
  });
});

function stripe_checkout(booking_id) {
  var handler = StripeCheckout.configure({
    key: 'pk_test_jPVRpCB1MLjWu2P71eTvXBZD',
    token: function(token) {
      // Send the charge through
      $.post("/charges/create", 
       { token: token.id, booking_id: booking_id }, function(data) {
        if (data["status"] == "ok") {
          window.location = "/some-url";
        } else {
          // Deal with error
          alert(data["message"]);
        }
      });
    }
  });
  return handler;
 }

# Bookings controller
class BookingsController < ApplicationController
  def show
    @booking = Booking.find(params[:id])
    attrs = @booking.attributes
    attrs.merge!("email" => current_user.email)

    respond_to do |format|
      format.json { render json: attrs.to_json }
    end
  end
end

# Charges controller
class ChargesController < ApplicationController

  def create
    booking = Booking.find(params[:booking_id])
    customer = Stripe::Customer.create(card: params[:token])

    charge = Stripe::Charge.create(
      customer:    customer.id,
      amount:      booking.amount,
      description: booking.description,
      currency:    'usd'
     )

    if charge.paid
      # Do some things for successful charge
      respond_to do |format|
        format.json { render json: {status: "ok"}.to_json }
      end
    else
      respond_to do |format|
        format.json { render json: {status: "fail", message: "Error with processing payment.  Please contact support."}.to_json }
      end
    end
  end
end

Wednesday 12 April 2017

create star rating using php

Create star rating example.

Here create fitst stat function and pass the value you want.

and you need font awsome css.

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<?php
function stars($all){
$whole = floor($all);
$fraction = $all - $whole;

if($fraction < .25){
$dec=0;
}elseif($fraction >= .25 && $fraction < .75){
$dec=.50;
}elseif($fraction >= .75){
$dec=1;
}
$r = $whole + $dec;

//As we sometimes round up, we split again
$stars="";
$newwhole = floor($r);
$fraction = $r - $newwhole;
for($s=1;$s<=$newwhole;$s++){
$stars .= "<span class='rating '><i class='fa fa-star' aria-hidden='true'></i></span>";
}
if($fraction==.5){
$stars .= "<span class='rating '><i class='fa fa-star-half-o' aria-hidden='true'></i></span>";
}


if($all!=""||$all!=0){
$gg  = 5-$all;



if($gg>=1 && $gg<2){

$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
}

if($gg>=2 && $gg<3){

$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
}

if($gg>=3  && $gg<4){

$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
}

if($gg>=4 && $gg<5){

$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
}

if($gg==5){

$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
}
}else{

$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";
$stars .= "<span class='rating'><i class='fa fa-star-o' aria-hidden='true'></i></span>";

}
return $stars;
}



echo  stars(0);
echo "<br/>";
echo  stars(1.5);
echo "<br/>";
echo  stars(2);
echo "<br/>";
echo  stars(3);
echo "<br/>";
echo  stars(4);
echo "<br/>";
echo  stars(5);

?>

Thursday 23 February 2017

Pretty Ajax Image Upload Example jquery and php

Hello

Example of image upload using ajax

in we needed  bootstrap.min.css,jquery.form.js,bootstrap.min.js,jquery.form.js,jquery-1.12.4.min.js,jquery-latest.js

first display here php page

pretty.php

<head>


<title>Pretty Ajax Image Upload  Example</title>
<script
              src="https://code.jquery.com/jquery-1.12.4.min.js"
              integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
              crossorigin="anonymous"></script>
              <script src="http://code.jquery.com/jquery-latest.js"/></script>
              <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.js"></script>
      
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="application/javascript">
$(document).ready(function(e) {
  
    $("#kichen_image_upload_link").click(function() {
        //alert();
        $("#kichen_image_upload_file").trigger('click');
    });

  
function onsuccess(response, status) {

        var result = $.parseJSON(response);
        //alert(result['message']);

        if (result['message'] == "sucess") {
            var imagepath = result['imagename'];
            $("ul.kichen_image_upload li:last").before('<li><a href="#"><img style="height:75px;width:75px;" src="' + imagepath + '" alt="Kitchen"></a></li>');
          
        var images_name =     $('input[name=hidden_kichen_select_image]').val();
      
        if(images_name!=''){
        var get_image = images_name+','+result['imagepath'];
        }else{
            var get_image = result['imagepath'];
        }
        $('input[name=hidden_kichen_select_image]').val(get_image);
      
        } else if (result['message'] == "images") {
            alert('Please select image only');
        } else if (result['message'] == "login") {
            alert('Please login as seller');
        }

        //$("#onsuccessmsg").html("Status :<b>"+status+'</b><br><br>Response Data :<div id="msg" style="border:5px solid #CCC;padding:15px;">'+response+'</div>');
    }

    $("#kichen_image_upload_file").change(function() {
        $("#kichen_image_upload_form").submit();


    });

    $("#kichen_image_upload_form").on('submit', function() {
        var options = {
            url: $(this).attr("action"),
            success: onsuccess
        };
        $(this).ajaxSubmit(options);
        return false;
    });
 });
</script>
<style>
ul li{
    margin:5px;
}
</style>
</head>

<body>

<ul class="kichen_image_upload" style="list-style:none;display:inline-flex;margin:10px;">
                    <li> <a id="kichen_image_upload_link" href="#"> <img src="kitchen5.jpg" alt="image"></a>
                      <form method="POST" action="image_upload.php" id="kichen_image_upload_form">
                        <input style="display:none;" type="file" id="kichen_image_upload_file" name="kichen_image_upload_file"/>
                        <input type="hidden" name="hidden_kichen_select_image"/>
                      </form>
                    </li>
                  </ul>

</body>


after in this ajax request file name is image_upload.php

$file = $_FILES['kichen_image_upload_file']['tmp_name'];
if (file_exists($file))
    {
        $file = $_FILES['kichen_image_upload_file']['tmp_name'];
        $imagesizedata = getimagesize($file);
        if ($imagesizedata === FALSE)
        {
            //not image
            $data['message'] = "images";
        }
        else
        {
       
           
            $full_path = "image/";
           
            if(!is_dir($full_path)){
                mkdir($full_path, 0777, true);
            }
            $path = $_FILES['kichen_image_upload_file']['tmp_name'];
           
            $image_name = $full_path.preg_replace( "/[^a-z0-9\._]+/", "-", strtolower($_FILES['kichen_image_upload_file']['name']) );
            move_uploaded_file($path,$image_name);
           
            $data['message'] ="sucess";
            $data['imagename'] =$image_name;
            $data['imagepath'] =$image_name;
           
            //print_r($imagesizedata);
            //image
            //use $imagesizedata to get extra info
        }
    }
    else
    {
        //not file
        $data['message'] = "images";
    }
    echo json_encode($data);
?>







Sunday 25 December 2016

Get User Media or Image in Your Instagram Example

Hello,


<?php

/* Get image in your instagram Account */

$set_scope_your_app ="https://www.instagram.com/oauth/authorize/?

client_id=Added-your-client_id&

redirect_uri=Added-your-redirect_uri&response_typ

e=code&scope=public_content";


$get_acess_token = "https://instagram.com/oauth/authorize/?

client_id=Added-your-client_id&

redirect_uri=Added-your-redirect_uri&respons

e_type=token";

$url="https://api.instagram.com/v1/users/self/media/recent/?access_token=Added-your-access_token";
 $json = file_get_contents($url);
$data = json_decode($json);


$images = array();
foreach( $data->data as $user_data ) {
    $images[] = (array) $user_data->images;
}

$standard = array_map( function( $item ) {
    return $item['standard_resolution']->url;
}, $images );

echo "<pre>";
print_r($standard);


echo "<pre>";
print_r($standard);

Thursday 1 December 2016

login with google with php example

login with google with php example

//login with google with php example

<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>
<script src="https://apis.google.com/js/api:client.js"></script>
<script>
var startApp1 = function() {
    gapi.load('auth2', function(){
      // Retrieve the singleton for the GoogleAuth library and set up the client.
      auth2 = gapi.auth2.init({
        client_id: 'your google client id',
        cookiepolicy: 'single_host_origin',
        // Request scopes in addition to 'profile' and 'email'
        //scope: 'additional_scope'
      });
      attachSignin1(document.getElementById('gplus1'));
    });
  };

  function attachSignin1(element) {
    console.log(element.id);
    auth2.attachClickHandler(element, {},
        function(googleUser) {

var facebook_email  = googleUser.getBasicProfile().getEmail();
var facebook_name = googleUser.getBasicProfile().getName();
var get_role_id = 2;
var facebook_login = 0;
  var google_login = 1;

        
               $.ajax({
url:"common/facebook_login",
method:"POST",
data:{facebook_email:facebook_email,facebook_login:facebook_login,google_login:google_login},
success: function(res){
if(jQuery.trim(res)=="Your are successfully login"){
//jQuery('.all_error_here').text(res);
//$("#errorDialog").modal('show');
location.reload();
}else{
jQuery('.all_error_here').text(res);
$("#errorDialog").modal('show');
}

}
});

        }, function(error) {
          alert(JSON.stringify(error, undefined, 2));
        });
  }
  </script>
 

  <script>startApp1();</script>
 
  <button id="gplus1" data-dismiss="modal" data-toggle="modal" class="btn btn-block radius-6 twitter-btn"><i class="fa fa-google-plus"></i> Sign in with Google+</button>

//login with google with php example

login with facebook with php example

login with facebook with php example

//login with facebook with php example
<script
  src="https://code.jquery.com/jquery-1.12.4.min.js"
  integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
  crossorigin="anonymous"></script>
<script type="application/javascript">

 

  window.fbAsyncInit = function() {
  FB.init({
    appId      : 'your facebook app id',
    cookie     : true,  // enable cookies to allow the server to access
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.8' // use graph api version 2.8
  });

  };
 

  // Load the SDK asynchronously
  (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'));
 
 
  // Pass function you want to login ur sing up;

  function checkLoginState(login) {
 
 
 

 
 
FB.login(function(response) {
    if (response.authResponse) {
   
  FB.api('/me?fields=id,name,email,permissions', function(response) {
                
var facebook_email  = response.email;
var facebook_name = response.name;
var get_role_id = 2;
var facebook_login = 1;
  var google_login = 0;
if(login == "login"){
  $.ajax({
url:"common/facebook_login",
method:"POST",
data:{facebook_email:facebook_email,facebook_login:facebook_login,google_login:google_login},
success: function(res){
if(jQuery.trim(res)=="Your are successfully login"){
//jQuery('.all_error_here').text(res);
//$("#errorDialog").modal('show');
location.reload();
}else{
jQuery('.all_error_here').text(res);
$("#errorDialog").modal('show');
}
//location.reload();
}
});
}else{
  $.ajax({
url:"common/facebook_signup",
method:"POST",
data:{facebook_email:facebook_email,facebook_name:facebook_name,get_role_id:get_role_id,facebook_login:facebook_login,google_login:google_login},
success: function(res){
/*if(jQuery.trim(res)=="sucess"){
jQuery('.all_error_here').text('Thank you for sign up');
$("#errorDialog").modal('show');
}else{
jQuery('.all_error_here').text(res);
$("#errorDialog").modal('show');
}*/
location.reload();
}
});
}
               });
    } else {
     console.log('User cancelled login or did not fully authorize.');
    }
}, { auth_type: 'reauthenticate' });
 
  }
 
 

</script>

<button data-dismiss="modal" data-toggle="modal" onclick="checkLoginState('login')" class="btn btn-block radius-6 facebook-btn"><i class="fa fa-facebook"></i> Sign in with Facebook</button>


//login with facebook with php example

Tuesday 15 November 2016

php and curl get put post delete example

php and  curl get put post delete example

hello here how to pass value in post and put curl in php. 
see the below example.

/*  PUT CURL EXAMPLE (php and  curl get put post delete example) */

$data = array('email'=>'test@test.com','password'=>'test');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);
echo "<pre>";
print_r($response);


/*  POST CURL EXAMPLE  (php and  curl get put post delete example)*/


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);
echo "<pre>";
print_r($response);

/*  GET CURL EXAMPLE  (php and  curl get put post delete example)*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo "<pre>";
print_r($response);

/*DELETE CURL EXAMPLE  (php and  curl get put post delete example)*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);
echo "<pre>";
print_r($response);

Tuesday 4 October 2016

convert column name into lowercase in mysql and php

Helllo

convert column name into lowercase in mysql and php

some time we want all table column name in lower case then we can change to manually but here
example you can paste this query after run query. you can change you column name in to lower case


convert column name into lowercase in mysql and php example start.

<?php
$c1 = mysql_connect("localhost","root","");// Connection




$db1 = mysql_select_db("INFORMATION_SCHEMA");



$get_column = mysql_query("SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='data_base_name' AND `TABLE_NAME`='table_name'");

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


$old_name = $row['COLUMN_NAME'];
$new_name = strtolower($row['COLUMN_NAME']);
$datatype= $row['DATA_TYPE'];
$size = $row['CHARACTER_MAXIMUM_LENGTH'];



if($row['DATA_TYPE'] !="varchar" && $row['DATA_TYPE'] !="text"){
$query =  "ALTER TABLE mstusers CHANGE $old_name $new_name $datatype".";<br/>";
}else{

$query =  "ALTER TABLE mstusers CHANGE $old_name $new_name $datatype ($size)".";<br/>";
}
echo $query;


}

// Query paste in your  phpmyadmin



?>

Please setup below code replace table_name with you table name and database_name replace with you
database name. also setup up your database connection.

After check all query for convert column name into lowercase in mysql and php.

i think it work for you.

convert column name into lowercase in mysql and php

Monday 3 October 2016

ajax image upload with form data in jquery and php

ajax image upload with form data in jquery and php


Hello Here example how to image upload using ajax using php.

and also know how to another value in ajax request.

ajax image upload with form data in jquery and php. please check below example to pass ajax data pass in jquery.

ajax image upload with form data in jquery and php

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="application/javascript">
$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();

        var formData = new FormData();
var text = $('input[type=text]').val();

formData.append('image', $('input[type=file]')[0].files[0]);
formData.append('test', text);


        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
$('#imageUploadForm')[0].reset();
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});
</script>
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    <input type="file" id="ImageBrowse"  name="image" size="30"/>
     <input type="text" id="text"  value="nice man" name="text" size="30"/>
    <input type="submit" name="upload" value="Upload" />
   
</form>
<?php
if(isset($_FILES['image'])){
if(!is_dir('ajax_image')){
mkdir('ajax_image');
}
echo "GET TEXT BOX VALUE = ".$_POST['test'];
$path = $_FILES['image']['tmp_name'];
$new = "ajax_image/".uniqid().$_FILES['image']['name'];
move_uploaded_file($path,$new);
}
 ?>

ajax image upload with form data in jquery and php