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/>";
?>



Wednesday 1 November 2017

only number or letter input in textbox using jquery example

only number or letter input in textbox using jquery example

you can set using this id and class name 

this example for if you want to input onlu number or letter other you can not enter this 

Please check this example
<script type="application/javascript">
$("input[name=number]").keydown(function (e) {

        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });


// only letter input using jquery

$("input[name=letter]").on("keydown", function(event){
  // Allow controls such as backspace, tab etc.
  var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];

  // Allow letters
  for(var i = 65; i <= 90; i++){
    arr.push(i);
  }

  // Prevent default if not in array
  if(jQuery.inArray(event.which, arr) === -1){
    event.preventDefault();
  }
});

</script>

<input type="text" name="number" placeholder="only number input" />
<input type="text" name="letter" placeholder="only letter input" />

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).

Saturday 16 September 2017

Create parking using jquery ui draggable and droppable

Create parking using jquery ui draggable and droppable

Create parking using jquery ui draggable and droppable


<!doctype html>
<html lang="en">
<head>
<title>Society Parking</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="parking.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>

<script type="application/javascript">
$( init );

function init() {



// Ajax Loader
$(document).bind("ajaxStart.mine", function() {

$('.se-pre-con').css("display","block");
});

$(document).bind("ajaxStop.mine", function() {

$('.se-pre-con').css("display","none");
});
// End Ajax Loader

// User draggable event
$(".ui-draggable").draggable({ cursor: "crosshair", revert: "invalid"});



// User droppable event
$("#cardSlots div").droppable({ accept: ".ui-draggable",
           drop: function(event, ui) {
var dropped = ui.draggable;
var droppedOn = $(this);
          

    if($( this ).hasClass('over')==false){
$(".ui-draggable").draggable({ cursor: "crosshair", revert: "invalid"}); // drop element can drag it
$(this).addClass("over"); // drop box add over class

// this code remove prvious element (last drop element data)
if($(ui.draggable).attr('previousid')!=undefined){

var previousid  = "#"+$(ui.draggable).attr('previousid');

$(previousid).removeClass("over");
 
var member = $(ui.draggable).attr('data-userid');
var flat = $(ui.draggable).attr('data-flat');
var hidden_blockid = $(ui.draggable).attr('data-block');
var hidden_parkind =  $(previousid).attr('data-parkid');
var left_p = $(ui.draggable).css('left');
var top_p = $(ui.draggable).css('top');
//alert(top_p);
var flag = "1";




/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,flag:flag},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}
});*/
 
}
// Ends


// this for delete previous element data
var ids =  $(this).attr('id'); // get id
$(ui.draggable).attr('previousid',ids); // set id

     ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } ); 

  // this code insert current parking element

var member = $(ui.draggable).attr('data-userid');
  var flat = $(ui.draggable).attr('data-flat');
  var hidden_blockid = $(ui.draggable).attr('data-block');
  var hidden_parkind =  $(this).attr('data-parkid');
  var left_p = $(ui.draggable).css('left');
   var top_p = $(ui.draggable).css('top');
var park_drop = ids;
  
/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,park_drop:park_drop},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}

});*/
//ends




}else{

$(".ui-draggable").draggable({ cursor: "crosshair", revert: true});

$("#cardPile").droppable({ accept: ".ui-draggable", drop: function(event, ui) {
console.log("drop");

var dropped = ui.draggable;
var droppedOn = $(this);
//$(dropped).detach().css("position","relative").appendTo(droppedOn);     
$(dropped).removeAttr('style');
$(dropped).css("position","relative");
var imageUrl = $(dropped).attr('data-image');
$(dropped).css('background-image', 'url(' + imageUrl + ')');
$(dropped).css(' background-repeat', 'no-repeat');
$(dropped).css('background-size', '55px 86px');
var left_posion =  $(this).attr('data-left_pos');
   var top_posion =  $(this).attr('data-top_pos');
  
   if(left_posion!=''&&top_posion!=''){
    $(this).css('left', left_posion);
$(this).css('top', top_posion);
  }
 
 
if($(ui.draggable).attr('previousid')!=undefined){

var previousid  = "#"+$(ui.draggable).attr('previousid');

$(previousid).removeClass("over");

var member = $(ui.draggable).attr('data-userid');
var flat = $(ui.draggable).attr('data-flat');
var hidden_blockid = $(ui.draggable).attr('data-block');
var hidden_parkind =  $(previousid).attr('data-parkid');
var left_p = $(ui.draggable).css('left');
var top_p = $(ui.draggable).css('top');
//alert(top_p);
var flag = "1";




/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,flag:flag},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}
});*/

}


},


});

}
           
            
                },
over: function(event, ui) {},

                  out: function(event, ui) {}
                     });

// this code after set data in parking the goto prvious position (set for user display list)
$("#cardPile").droppable({ accept: ".ui-draggable", drop: function(event, ui) {
console.log('drop sucess');

var dropped = ui.draggable;
var droppedOn = $(this);

$(dropped).removeAttr('style');

$(dropped).css("position","relative");

var imageUrl = $(dropped).attr('data-image');
$(dropped).css('background-image', 'url(' + imageUrl + ')');
$(dropped).css(' background-repeat', 'no-repeat');
$(dropped).css('background-size', '55px 86px');

if($(ui.draggable).attr('previousid')!=undefined){

var previousid  = "#"+$(ui.draggable).attr('previousid');

$(previousid).removeClass("over");

var member = $(ui.draggable).attr('data-userid');
var flat = $(ui.draggable).attr('data-flat');
var hidden_blockid = $(ui.draggable).attr('data-block');
var hidden_parkind =  $(previousid).attr('data-parkid');
var left_p = $(ui.draggable).css('left');
var top_p = $(ui.draggable).css('top');
//alert(top_p);
var flag = "1";




/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,flag:flag},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}
});*/

}

$(ui.draggable).removeAttr('previousid');



}


});

// set background image to all userlist box
$(".profileimg").each(function(index, element) {
var imageUrl =   $(this).attr('data-image');
$(this).css('background-image', 'url(' + imageUrl + ')');
$(this).css(' background-repeat', 'no-repeat');
$(this).css('background-size', '55px 86px');

var left_posion =  $(this).attr('data-left_pos');
var top_posion =  $(this).attr('data-top_pos');

if(left_posion!=''&&top_posion!=''){
$(this).css('left', left_posion);
$(this).css('top', top_posion);
}
            });



}
</script>
<div id="loader" class="se-pre-con"></div>
<div id="wrapper">


       


  <div id="cardPile">
        <div  data-left_pos="" data-top_pos="" data-userid="11" data-flat="1" data-block="1" id="card11" data-image="thumb_59b7e0eeb0b6125-dsc-4806-copy-1490189640.jpg" class="ui-draggable profileimg"> </div>
        <div previousid=droppable24 data-left_pos="192px" data-top_pos="236px" data-userid="17" data-flat="1" data-block="1" id="card17" data-image="thumb_59b7e135e97524331AD0C00000578-4784672-image-m-2_1502551607375.jpg" class="ui-draggable profileimg"> </div>
        <div previousid=droppable23 data-left_pos="56px" data-top_pos="236px" data-userid="18" data-flat="1" data-block="1" id="card18" data-image="thumb_59b7e0175dc18Salman-Khan_55.jpg" class="ui-draggable profileimg"> </div>
      </div>
  <div id="cardSlots" style="width:910px;">
        <div  class="ui-droppable cardSlots " id="droppable6" data-parkid="6"   >a1011</div>
        <div  class="ui-droppable cardSlots " id="droppable7" data-parkid="7"   >a101</div>
        <div  class="ui-droppable cardSlots " id="droppable8" data-parkid="8"   >708</div>
        <div  class="ui-droppable cardSlots " id="droppable10" data-parkid="10"   >701</div>
        <div  class="ui-droppable cardSlots " id="droppable11" data-parkid="11"   >702</div>
        <div  class="ui-droppable cardSlots " id="droppable12" data-parkid="12"   >703</div>
        <div  class="ui-droppable cardSlots " id="droppable13" data-parkid="13"   >704</div>
        <div  class="ui-droppable cardSlots " id="droppable14" data-parkid="14"   >705</div>
        <div  class="ui-droppable cardSlots " id="droppable15" data-parkid="15"   >706</div>
        <div  class="ui-droppable cardSlots " id="droppable16" data-parkid="16"   >7014</div>
        <div  class="ui-droppable cardSlots " id="droppable17" data-parkid="17"   >707</div>
        <div  class="ui-droppable cardSlots " id="droppable18" data-parkid="18"   >709</div>
        <div  class="ui-droppable cardSlots " id="droppable19" data-parkid="19"   >7011</div>
        <div  class="ui-droppable cardSlots " id="droppable20" data-parkid="20"   >7012</div>
        <div  class="ui-droppable cardSlots " id="droppable21" data-parkid="21"   >501</div>
        <div  class="ui-droppable cardSlots " id="droppable22" data-parkid="22"   >503</div>
        <div  class="ui-droppable cardSlots over" id="droppable23" data-parkid="23"   >504</div>
        <div  class="ui-droppable cardSlots over" id="droppable24" data-parkid="24"   >505</div>
        <div  class="ui-droppable cardSlots " id="droppable25" data-parkid="25"   >506</div>
        <div  class="ui-droppable cardSlots " id="droppable26" data-parkid="26"   >507</div>
        <div  class="ui-droppable cardSlots " id="droppable27" data-parkid="27"   >508</div>
        <div  class="ui-droppable cardSlots " id="droppable28" data-parkid="28"   >509</div>
        <div  class="ui-droppable cardSlots " id="droppable29" data-parkid="29"   >5010</div>
        <div  class="ui-droppable cardSlots " id="droppable30" data-parkid="30"   >101</div>
        <div  class="ui-droppable cardSlots " id="droppable31" data-parkid="31"   >102</div>
        <div  class="ui-droppable cardSlots " id="droppable32" data-parkid="32"   >103</div>
        <div  class="ui-droppable cardSlots " id="droppable33" data-parkid="33"   >104</div>
        <div  class="ui-droppable cardSlots " id="droppable34" data-parkid="34"   >105</div>
        <div  class="ui-droppable cardSlots " id="droppable35" data-parkid="35"   >107</div>
        <div  class="ui-droppable cardSlots " id="droppable36" data-parkid="36"   >108</div>
        <div  class="ui-droppable cardSlots " id="droppable37" data-parkid="37"   >109</div>
        <div  class="ui-droppable cardSlots " id="droppable38" data-parkid="38"   >110</div>
        <div  class="ui-droppable cardSlots " id="droppable39" data-parkid="39"   >111</div>
        <div  class="ui-droppable cardSlots " id="droppable40" data-parkid="40"   >113</div>
        <div  class="ui-droppable cardSlots " id="droppable41" data-parkid="41"   >114</div>
        <div  class="ui-droppable cardSlots " id="droppable42" data-parkid="42"   >301</div>
        <div  class="ui-droppable cardSlots " id="droppable43" data-parkid="43"   >222</div>
      
  </div>
  <!--<div id="drop" class="fbox">
  
</div>-->
</div>

Monday 21 August 2017

Get wordpress post using webservice

Get wordpress post using webservice


Get wordpress post using webservice, wordpress, wordpress websevice, get post using webservice, 



<?php

require_once '../wp-load.php';
require_once '../wp-config.php';
header('Content-type: application/json');

$response = array();
$count = 0;

$args = array(
        'post_type' => 'owl-carousel',
'posts_per_page' => -1,
        'orderby' => get_option('owl_carousel_orderby', 'post_date'),
        'order' => 'asc',
        'tax_query' => array(
            array(
                'taxonomy' => 'Carousel',
                'field' => 'slug',
                'terms' => 'home'
            )
        ),
        'nopaging' => true
    );

$my_query = null;
$my_query = new WP_Query($args);

if( $my_query->have_posts() )
{
$response['message'] = 'Banner list';
$response['status'] = 1;

while ($my_query->have_posts()) : $my_query->the_post();
   
$response['data'][$count]['id'] = get_the_ID();
$response['data'][$count]['title'] = html_entity_decode(get_the_title());
$response['data'][$count]['imageurl'] = wp_get_attachment_url( get_post_thumbnail_id($my_query->ID));
$count++;

endwhile;
}
else
{
$response['message'] = 'No banner exists.';
$response['status'] = 2;
}

echo json_encode($response);

?>

Insert webservice with post type with metabox value in wordpress

Insert webservice with post type with metabox value in wordpress

Insert webservice with post type with metabox value in wordpress, wordpress, wordpress webserivce, insert webserice in wordpress, 

<?php

require_once '../wp-load.php';
require_once '../wp-config.php';
header('Content-type: application/json');

$response = array();


$alu_name=    sanitize_meta('name_alu_c1',$_POST['metal_name'],'user');
$alu_email=    sanitize_email($_POST['metal_email']);
$alu_mobile=    sanitize_meta('phone_alu_c1',$_POST['metal_mobile'],'user');
$alu_city=    sanitize_meta('city_alu_c1',$_POST['metal_city'],'user');
$alu_message=    sanitize_meta('message_alu_c1',$_POST['metal_message'],'user');





$my_cptpost_args = array(
          
            'post_title' => $alu_name,
            'post_status'   => 'publish',
            'post_type' => "enter-your-post-type-name",
);

$admin_email = "admin@gmail.com";
$headers[] = 'From: <test@gmail.com>';
$second_email = "test@gmail.com";

$cpt_id = wp_insert_post($my_cptpost_args, $wp_error );
if($cpt_id){

$response['message'] = 'Thank you! We will get back to you soon.';
$response['status'] = 1;
add_post_meta($cpt_id, 'name_alu_c1', $alu_name, true);//here insert two custom field data.
add_post_meta($cpt_id, 'email_address_alu_c1', $alu_email, true);//here insert two custom field data.
add_post_meta($cpt_id, 'phone_alu_c1', $alu_mobile, true);//here insert two custom field data.
add_post_meta($cpt_id, 'city_alu_c1', $alu_city, true); //here insert two custom field data..
add_post_meta($cpt_id, 'message_alu_c1', $alu_message, true); //here insert two custom field data..

$email_temp = "Name : ".$alu_name."<br/>";
$email_temp .= "Email : ".$alu_email."<br/>";
$email_temp .= "Phone : ".$alu_mobile."<br/>";
$email_temp .= "City : ".$alu_city."<br/>";
$email_temp .= "Message : ".$alu_message."<br/>";

$inqury = " Inquiry for ".$alu_name;

$test = wp_mail( $alu_email, "Contact Us", "Thank you! We will get back to you soon.",$headers);
$test = wp_mail($admin_email, $inqury, $email_temp );
if($second_email !=''){
$test = wp_mail($second_email, $inqury, $email_temp );
}


}else{

$response['message'] = 'Some Error';
$response['status'] = 2;

}


echo json_encode($response);

?>


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 19 July 2017

Get posts using wordpress rss feed url and add featured post thumbnails in WordPress feeds

Get posts using wordpress rss feed url and add featured post thumbnails in WordPress feeds


Hello

here the example of geting data from rss feed url

this code in your current wordpress function.php file 
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
    global $post;
    if( has_post_thumbnail( $post->ID ) ) {
        $content = '<p>' . get_the_post_thumbnail( $post->ID ) . '</p>' . $content;
    }
    return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );

$url = 'Your Wordpress Rss Fedd';

    $rss = new DOMDocument();
    $rss->load($url);
    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array (
                'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                'description' => $node->getElementsByTagName('description')->item(0)->nodeValue,
                'content' => $node->getElementsByTagName('encoded')->item(0)->nodeValue

                );
       array_push($feed, $item);
    }



  
  
 
foreach($feed as $f){
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $f['description'], $image);

   $content = strip_tags(preg_replace("/<img[^>]+\>/i", "", $image[0]),"</p>");
  
$pos = strrpos( $content, '[');
echo  $image['src']; // Get Feature image in rss
echo $f['link']; // Get Link in post
echo $f['title']; // get Title of post
echo $f['pubDate']; // get Publish date
echo rtrim (substr($content, 0, $pos) ); // Only get description


}

Wednesday 28 June 2017

how to file delete in s3 bucket in aws in codeniter


how to file delete in s3 bucket in aws in codeigniter


//

Controller


public function seller_kichen_delete(){
       
       
            $replace_image_value = $this->input->post('replace_image_value');
           
            $data = s3_bucket_delete($replace_image_value);
       
    }
   
    // add this code in heleper
    function s3_bucket_delete($temppath){
        $bucket = "bucket-name";
       
        try{
           
           
            $s3Client = new S3Client([
            'version'     => 'latest',
            'region'      => 'us-west-2',
            'credentials' => [
            'key'    => 'key',
            'secret' => 'secret-key',
            ],
            ]);
       
           
                $result = $s3Client->deleteObject([
                'Bucket' => $bucket,
                'Key' => $temppath,
                ]);
                    $data['message'] =  "success";
           
    } catch (Exception $e) {
            $data['message'] =  "false";
            // echo $e->getMessage() . "\n";
            }
           
           
       
        return $data;
       
    }

how to image and file upload using aws bucket in codeigniter

how to image and file upload using aws bucket in codeigniter 

public function profile_upload(){


//print_r($_FILES);

if($this->session->userdata('user_login')){


$file = $_FILES['agent_profile_file']['tmp_name'];

    if (file_exists($file))
    {
         $allowedExts = array("gif", "jpeg", "jpg", "png");
$typefile = explode(".", $_FILES["agent_profile_file"]["name"]);
     $extension = end($typefile);

        if (!in_array(strtolower($extension),  $allowedExts))
        {
            //not image
$data['message'] = "images";
        }
        else
        {
$userid =  $this->session->userdata['user_login']['userid'];

$full_path = "agent_image/".$userid."/profileImg/";

/*if(!is_dir($full_path)){
mkdir($full_path, 0777, true);
}*/
$path = $_FILES['agent_profile_file']['tmp_name'];

$image_name = $full_path.preg_replace( "/[^a-z0-9\._]+/", "-", strtolower(uniqid().$_FILES['agent_profile_file']['name']) );
//move_uploaded_file($path,$image_name);



$data['message'] ="sucess";


$s3_bucket = s3_bucket_upload($path,$image_name);


if($s3_bucket['message']=="sucess"){
$data['imagename'] =$s3_bucket['imagepath'];
$data['imagepath'] =$s3_bucket['imagename'];
}

//print_r($imagesizedata);
            //image
            //use $imagesizedata to get extra info
        }
    }
    else
    {
        //not file
$data['message'] = "images";
    }

}else{
$data['message'] = "login";
}
echo json_encode($data);
//$file_name2 = preg_replace("/ /", "-", $file_name);


}
  // Helper file add code 
    // image compress code
function compress($source, $destination, $quality) {

ob_start();
$info = getimagesize($source);

if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);

elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);

elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);

$filename = tempnam(sys_get_temp_dir(), "beyondbroker");

imagejpeg($image, $filename, $quality);

      //ob_get_contents();
$imagedata =ob_end_clean();
return $filename;
}
   
    // type for if image then it will reduce size
    // site for it in web of mobile because mobile webservice image will in base 64
    // $tempth will file temp path
    // $image_path will file where to save path
   
    function s3_bucket_upload($temppath,$image_path,$type="image",$site="web"){
$bucket = "bucket-name";

$data =array();

$data['message'] =  "false";


// For website only
if($site=="web"){
if($type=="image"){

  $file_Path = compress($temppath,$image_path,90);
 
}else{
  $file_Path =$temppath;
}
}

try{


$s3Client = new S3Client([
'version'     => 'latest',
'region'      => 'us-west-2',
'credentials' => [
'key'    => 'aws-key',
'secret' => 'aws-secretkey',
],
]);

// For website only
if($site=="web"){

$result = $s3Client->putObject([
'Bucket'     => $bucket,
'Key'        => $image_path,
'SourceFile' => $file_Path,
//'body'=> $file_Path,
'ACL'          => 'public-read',
//'StorageClass' => 'REDUCED_REDUNDANCY',
]);

$data['message']  = "sucess";
$data['imagename']  = $image_path;
$data['imagepath']  = $result['ObjectURL'];
}else{

// $tmp = base64_decode($base64);
$upload = $s3Client->upload($bucket, $image_path, $temppath, 'public-read');
$data['message']  = "sucess";
$data['imagepath']  = $upload->get('ObjectURL');


}


} catch (Exception $e) {
$data['message'] =  "false";
// echo $e->getMessage() . "\n";
}



return $data;
}

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