How to get the id automatically in db - php

I am doing a api for cab booking app like uber and ola using laravel.In that the customer will send the request to available cab driver using gcm and cab driver will accept the request.During these process when customer click the request button it will be loading until driver accept the request.When driver accept the request customer get the driver details and driver get the customer details.How can i do it in laravel..??
I can send the customer request using below code:
public function customer_booking(Request $req)
{
if ($req->isMethod('post'))
{
$customer_id=$req->customer_id;
$driver_type=$req->type_id;
//getting driver
$res=DriverLatLongModel::where('driver_type',$driver_type)
->where('booking_status','3')->orwhere('booking_status','2')
->where('active_status','0')->orderBy('created_at', 'desc')->first();
$driver_lat='';
$driver_long='';
$driver_id_booking='';
if(empty($res))
{
$gcm_data[]=array('status'=>'0');
return Response::json(array('message'=>$gcm_data), 200);
}
else
{
$driver_id_booking=$res->driver_id;
}
$registration_id = array();
//getting gcm id
$driver_position = DriverLatLongModel::where('driver_id',$driver_id_booking)->get();
foreach($driver_position as $resid)
{
array_push($registration_id , $resid['registration_id']);
}
//send gcm
$url = 'https://android.googleapis.com/gcm/send';
$message_gcm = array("Status"=>"1","Notice" =>"WELCOME","customer_id"=>$customer_id);
$fields = array(
'registration_ids' => $registration_id ,
'data' => $message_gcm ,
);
$headers = array(
'Authorization: key=AIzaSyDCDmsrv3ELqD_6qseFgERciRnmm9uBtNg',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
$driver_data=array();
//getting result of driver side
$finding_donor_loc=CustomerBookingModel::getCustomer($customer_id);
if(empty($finding_donor_loc))
{
$driver_data[]=array('status'=>'0');
}
else
{
//getting driver details
$driver_details=DriverDetailsModel::where('driver_id',$finding_donor_loc)->first();
$driver_name=$driver_details->driver_name;
$driver_data[]=array('status'=>'1','driver_name'=>$driver_name);
}
return Response::json(array('message'=>$driver_data), 200);
}
}
I am using Helper class to write the codeing for waiting until the driver accept the request:
public static function getCustomer($customer_id)
{
$duration =15; // Duration of the loop in seconds
$sleep = 5;// Sleep beetween each execution (with stuff execution)
for ($i = 0; $i < floor($duration / $sleep); ++$i)
{
$start = microtime(true);
$users = DB::table('booking_information')
->where('customer_id',$customer_id)->where('booking_status','1')
->where('book_confirm','1')->orderBy('created_at', 'asc')->first();
time_sleep_until($start + $sleep);
}
if(empty($users))
{
$confim_driver_id='0';
return $confim_driver_id;
}
else
{
$confim_driver_id=$users ->driver_id;
return $confim_driver_id;
}
}
The helper class do the work of get the driver id when they accept the request within 15 seconds.It's work for me but the driver will accept the request within 15 seconds.How can i do without time duration to check the db if driver id present or not and also it will loading in customer side until driver accept the request.!!

If you want to return the booking confirmation to user as soon as the booking is confirmed then you can put a IF condition in your for loop & return the driver_id as soon as the conditions are satisfied.
$duration = 15; // Duration of the loop in seconds
$sleep = 5; // Sleep between each execution (with stuff execution)
for ($i = 0; $i < floor($duration / $sleep); ++$i)
{
$start = microtime(true);
// query the database to check if the booking is confirmed
$booking = DB::table('booking_information')
->where('customer_id', $customer_id)
->where('booking_status', '1')
->where('book_confirm', '1')
->orderBy('created_at', 'asc')
->first();
// if the booking is confirmed then return the driver_id
// return will also stop the loop
if($booking) {
return $booking->driver_id;
}
// Make the script execution sleep
time_sleep_until($start + $sleep);
}
// if booking is not confirmed then return 0
if(empty($booking)) return 0;
A better way to do a task like this in laravel can be achieved via Events & Listeners. The workflow would be something like this.
1. Your API recieves a request to book a cab
2. A NewBookingRequest event is fired & NewBookingRequestListener sends a push notificaton to the nearest driver about the new booking
3. Driver confirms/denies the booking & your API fires BookingConfirmed/BookingDenied event
4. Notification is sent to the user about the booking

Related

SMS Reminder remain from Server Side in php

what is doing on SMS send Reminder to remain from Server Side for package end within 7 days or less than 10 days? any code or example video how to implement query.
I want the alert will come out about 2 weeks before the expiry date.
Many Paid SMS api available in online.
Here i'm using SmsHorizon
// Replace with your username
$user = "yourname";
// Replace with your API KEY (We have sent API KEY on activation email, also available on panel)
$apikey = "ABCBEFGH786756";
// Replace if you have your own Sender ID, else donot change
$senderid = "WEBSMS";
// For Plain Text, use "txt" ; for Unicode symbols or regional Languages like hindi/tamil/kannada use "uni"
$type = "txt";
// Database Configuration
$con = mysql_connect("143.114.0.49","username","password");
$con_db = mysql_select_db("db_name",$con);
/***********************Over Speed Alert***/ //Run every 1 minute
$i = 0;
$message = "2 Week Before Expiry Alert.\n" ;
$device_query = mysql_query("SELECT * FROM table_name); // Write whatever the query you've required.
while($device_value = mysql_fetch_array($device_query))
{
$message.= ""; // Content you load here.
$i++;
}
// Replace with the destination mobile Number to which you want to send sms
$mobile = array('9999999999');
// Replace with your Message content
$message = urlencode($message);
if($i > 0)
{
for($j = 0; $j < count($mobile); $j++)
{
$ch = curl_init("http://smshorizon.co.in/api/sendsms.php?user=".$user."&apikey=".$apikey."&mobile=".$mobile[$j]."&senderid=".$senderid."&message=".$message."&type=".$type."");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//$output = curl_exec($ch);
if(curl_errno($ch))
{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
// Display MSGID of the successful sms push
//echo $output;
}
}
Hope it help you.

How to resend android push notification first try failed

I have this methode :
$oAndroidService = new GoogleGNCService($message);
# divide per batch with 1000 users
$a_batch = array_chunk($a_users, 1000);
for($i = 0; $i < count($a_batch); $i++){
# get the liste of tokens
foreach($a_batch[$i] as $batch){
$a_tokens[] = $batch['token'];
}
# if push sent with success
if($oAndroidService->sendPush($a_tokens)){
foreach($a_batch[$i] as $userToProcess){
// update push token history
}
}
echo 'PUSH SENT !';
# unset the array with tokens
unset($a_tokens);
}else{
echo 'ERROR SENT PUSH'
}
}
And the method that sent pushes :
public function sendPush($a_token){
# init the curl connection
$ch = curl_init();
# if success connection
if($ch){
# array that will be send in post with curl call
$a_post = array(
'registration_ids' => $a_token,
'data' => $this->getMessage(),
);
# set the options of curl request
curl_setopt($ch, CURLOPT_URL, self::ANDROID_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($a_post));
# execute the request
$result = curl_exec($ch);
if($result === false){
echo('Curl failed : ' . curl_error($ch));
return false;
}
# close the request
curl_close($ch);
return true;
}
echo 'Connection failed';
return false;
}
I have 2 questions :
If I sent 1000 tokens and curl failed, I need to resend this array with tokens one more time ? If failed the second time, I need to resent third time ?
If curl failed how to know what are the token that poses problems ?
Thx for you help in advance

determine and sort distance for several locations

I have about 15 locations in a mysql table with lat and long information.
Using PHP and google maps API Am able to calculate distance between 2 locations.
function GetDrivingDistance($lat1, $lat2, $long1, $long2)
{
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['text'];
return array('distance' => $dist, 'time' => $time);
}
I want to to select one as fixed e.g. row 1 given lat and long
$query="SELECT lat, long from table WHERE location=1"
$locationStart = $conn->query($query); =
I want to calculate the distance to all other locations in the tables (other rows) and return the the outcome sorted by distance
tried to calculate each one alone and end up with very long code and takes too long to fetch that via api, also still not able to sort them this way!
any hint?
Disclaimer: This is not a working solution, nor have I tested it, it is just a quick example I've done off the top of my head to provide a sort of code sample to go with my comment.
My brains still not fully warmed up, but I believe the bottom should at least act as a sort of guide to help put across the idea I was making in my comment, i'll try to answer any questions you have when I'm free. Hope it helps.
<?php
define('MAXIMUM_REQUEST_STORE', 5); // Store 5 requests in each multi_curl_handle
function getCurlInstance($url) {
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
return $handle;
}
$data = []; // Build up an array of Endpoints you want to hit. I'll let you do that.
// Initialise Variables
$totalRequests = count($data);
$parallelCurlRequests = [];
$handlerID = 0;
// Set up our first handler
$parallelCurlRequests[$handlerID] = curl_multi_init();
// Loop through each of our curl handles
for ($i = 0; $i < $totalRequests; ++$i) {
// We want to create a new handler/store every 5 requests. -- Goes off the constant MAXIMUM_REQUEST_STORE
if ($i % MAXIMUM_REQUEST_STORE == 1 && $i > MAXIMUM_REQUEST_STORE) {
++$handlerID;
}
// Create a Curl Handle for the current endpoint
// ... and store the it in an array for later use.
$curl[$i] = getCurlInstance($data[$i]);
// Add the Curl Handle to the Multi-Curl-Handle
curl_multi_add_handle($parallelCurlRequests[$handlerID], $curl[$i]);
}
// Run each Curl-Multi-Handler in turn
foreach ($parallelCurlRequests as $request) {
$running = null;
do {
curl_multi_exec($request, $running);
} while ($running);
}
$distanceArray = [];
// You can now pull out the data from the request.
foreach ($curl as $response) {
$content = curl_multi_getcontent($response);
if (!empty($content)) {
// Build up some form of array.
$response = json_decode($content);
$location = $content->someObject[0]->someRow->location;
$distance = $content->someObject[0]->someRow->distance;
$distanceArray[$location] = $distance;
}
}
natsort($distanceArray);

Instagram API - How to check last page last record?

I am working on Instagram API first time and also using social media API first time so I have very basic knowledge of how to call and read data from API. So I have created one recursive function to call next page and read data. Now I am storing Media ID, Comments Counts, Likes Counts for each and every post data with next page in my instagram database table. Now I want to insert one another record to my schedule table when API reached to last page and inserted all records to instagram table. I am adding my code below and I will happy if someone guide me to make code more proper :)
My Code Work:
public function User($next=null){
global $TotalHashTagPosts; // Total hashtag post counts
global $CommentsSum; // Sum of comments
global $LikesSum; // Sum of likes
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/users/481959735/media/recent/?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
curl_setopt($Ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($Ch, CURLOPT_SSL_VERIFYPEER, 0);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
if(isset($Result->data)){
$Data = $Result->data;
for($i=0; $i<count($Data); $i++){
if(empty($Data)){
continue;
}
$LikesSum = $Data[$i]->likes->count; // Get likes total per media
$CommentsSum = $Data[$i]->comments->count; // Get comments total per media
$InstagramId = $Data[$i]->user->id; // Get media instagrammer id
$MediaId = $Data[$i]->id; // Get media id
$data = array(
'instagram_id' => $InstagramId,
'media_id' => $MediaId,
'comments_count' => $CommentsSum,
'likes_count' => $LikesSum,
'created_date' => date(DATE_YYYYMMDDHMS_24),
'status' => '1'
);
$this->db->insert('instagrammer_table', $data);
if($this->db->affected_rows() > 0){
echo "Insert successful";
}else{
echo "Failed to insert record";
}
}
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->User($next);
}else{
$NextUrl = "";
}
}
}

Too many sockets open by cURL multi

I am using cURL multi to get data from some websites. With code:
function getURL($ids)
{
global $mh;
$curl = array();
$response = array();
$n = count($ids);
for($i = 0; $i < $n; $i++) {
$id = $ids[$i];
$url = 'http://www.domain.com/?id='.$id;
// Init cURL
$curl[$i] = curl_init($url);
curl_setopt($curl[$i], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl[$i], CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl[$i], CURLOPT_USERAGENT, 'Googlebot/2.1 (http://www.googlebot.com/bot.html)');
//curl_setopt($curl[$i], CURLOPT_FORBID_REUSE, true);
//curl_setopt($curl[$i], CURLOPT_HEADER, false);
curl_setopt($curl[$i], CURLOPT_HTTPHEADER, array(
'Connection: Keep-Alive',
'Keep-Alive: 300'
));
// Set to multi cURL
curl_multi_add_handle($mh, $curl[$i]);
}
// Execute
do {
curl_multi_exec($mh, $flag);
} while ($flag > 0);
// Get response
for($i = 1; $i < $n; $i++) {
// Get data
$id = $ids[$i];
$response[] = array(
'id' => $id,
'data' => curl_multi_getcontent($curl[$i])
);
// Remove handle
//curl_multi_remove_handle($mh, $curl[$i]);
}
// Reponse
return $response;
}
But, i have problem is cURL open too many sockets to connect to webserver. Each connection, cURL create new socket to webserver.
I want to current connection is keep-alive for next connection. I don't want that 100 URL then cURL must create 100 sockets to handle :(
Please help me. Thanks so much !
So don't open that many sockets. Modify your code to only open X sockets, and then repeatedly use those sockets until all of your $ids have been consumed. That or pass fewer $ids into the function to begin with.
I know, this is old, but the correct answer has not been given, yet, IMHO.
Please have a look at th CURLMOPT_MAX_TOTAL_CONNECTIONS option, which should solve your problem:
https://curl.se/libcurl/c/CURLMOPT_MAX_TOTAL_CONNECTIONS.html
Also make sure, that multiplexing via HTTP/2 is not disabled accidentally:
https://curl.se/libcurl/c/CURLMOPT_PIPELINING.html
Classical HTTP/1 pipelining is no longer supported by cURL, but cURL can still re-use an existing HTTP/1 connection to send a new request once the current request has finished on that connection.

Categories