I get an undefined offset after passing the requests into the function - laravel

I'm trying to get the time taken to reach a distance using google distantmatrix.I get this error after passing the the required arguments into the function.
Public function GetDrivingDistance($lat1, $lat2, $long1, $long2) {
$data1 = setting::where('id',1)->first();
$key = $data1->key;
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL"."&key=".$key;
$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);
}
Error:
undefined offset: 0
At $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];

Try using data_get helper function like this:
$dist = data_get($response_a, 'rows.0.elements.0.distance.text');
$time = data_get($response_a, 'rows.0.elements.0.duration.text');
Using data_get method, null will be returned if the specified key is not found instead of getting an error.
See Laravel docs for more info.

Related

reCaptcha V2 is now timing out during valication

I have been using reCaptcha V2 for awhile now and all of a sudden the validation is timing out on the file_get_contents line.
I can copy the URL from the error and paste it into a new window and the JSON object comes back immediately.
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='. urlencode($secret) .'&response='. urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
I fixed this timeout problem with the File_get_contents by changing to using $curl instead.
Like this:
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secret) . '&response=' . urlencode($captcha);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// file get contents not used any more
//$response = file_get_contents($url,0,stream_context_create(["http"=>["timeout"=>120]]) );
$responseKeys = json_decode($response,true);
// should return JSON with success as true

Mock Curl response for testing in laravel

I am trying to unit test a function(updateMeeting) in laravel which uses a curl request inside it. I tried many google links but nothing worked. can you guys give me suggestions on this matter.
following are relevant methods. $this->meeting is a MeetingModel
public function updateMeeting($meetingId){
$meeting = $this->meeting->find($meetingId);
$endpoint = \Config::get('api_backend_endpoint');
$response = $this->curlPut($endpoint);
if ($response->http_status_code != 200) {
if(Input::get('source') == 'ajax') {
$apiResponse = app(ApiResponse::class);
$message = 'ERROR Updating Meeting ' . $meeting->name;
return $apiResponse->failed($message);
}
return Redirect::route('meetings.show', $meetingId)
->withInput()
->with('message', 'An error occurred hiding meeting with message: ' . $response->errors);
}
$meeting->save();
}
following is curlPut method
private function curlPut($url, $payload = array())
{
$data_string = json_encode($payload);
$ch = curl_init();
//send through our payload as post fields
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$buffer = json_decode(curl_exec($ch));
curl_close($ch);
return $buffer;
}
Use a webservice like https://www.mocky.io/. Instead of requesting the real API, you send your requests to their API. You can create mock endpoints which return a response you can define.

Adding a note for a subscriber using Mailchimp API

I am having trouble adding a note to a subscriber using Mailchimp's API. Here's what I have:
$email = 'some#email.com';
$list = '123456';
$note = 'This is an example of a note.';
$apiKey = 'MY-API-KEY';
$memberId = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://'.$dataCenter.'.api.mailchimp.com/3.0/lists/'.$list.'/members/'.$memberId.'/notes';
$json['note'] = $note;
$json = json_encode($json);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return true;
} else {
return false;
}
Any ideas why these notes would not be saved? I've made sure the API key, the list ID and the email address are all correct.
The documentation page is here: https://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/notes/

How to upload image from one domain to another?

I have two domain one is stgportal and another is stg.I want to upload image from stgportal to stg.My code is given below
move_uploaded_file($_FILES['ThumbnailImage']['tmp_name'],"http://stg.eminencesystem.com/assets/images/th/".$thimg)
show the error: failed to open stream: HTTP wrapper does not support writeable connections
how can i resolve this issue?
You can use CURL to send file to another server securely like this
At stgportal side
function sendImageToServer($path = "", $file = null)
{
$post_url = "http://stg.eminencesystem.com/post_file";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $post_url);
//most importent curl assues #filed as file field
$post_array = array(
"folder_name" => $path
);
if ((version_compare(PHP_VERSION, '5.5') >= 0)) {
$post_array['file'] = new CURLFile($file);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, TRUE);
} else {
$post_array['file'] = "#" . $file;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
$response = curl_exec($ch);
return $response;
}
At stg side
$ImagePath = "/var/www/html/assets/";
$files = $_FILES;
$folder_name = utf8_decode($_POST['folder_name']);
$savepath = $ImagePath . $folder_name . $files['name'];
copy($file['tmp_name'], $savepath);
echo 1;
exit;

How you should retrieve google plus +1 count for an url?

Using the rpc method:
$url = 'http://www.google.com';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
echo intval( $json[0]['result']['metadata']['globalCounts']['count'] );
or using the +1 button scrapping method?
$url = 'http://www.google.com';
$result = file_get_contents('https://plusone.google.com/_/+1/fastbutton?url='.urlencode($url));
preg_match( '/window\.__SSR = {c: ([\d]+)/', $result, $matches );
echo (isset($matches[0])) ? (int) str_replace('window.__SSR = {c:', '', $matches[0]) : 0;
Having an explanation of differences or possible side effects would be great.
Note: Both methods works as 2014/04/05.
Given that neither are official / supported by Google, I'd propably use the first method and fallback to the second in case that fails. The second method is more error-prone, since you're parsing source code that can change at any time (not that calling a service you're not supposed to be calling is any better, but apparently there are no other options).

Resources