retrieve google image search using foreach - image

I used the following function to get google search images
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
It works good when I output all results using print_r()
$images = get_images("porsche");
print_r($images);
But when I want to get a specific value using foreach()
foreach ($images->responseData->results as $result) {
echo $result->url;
}
I got an error:
Notice: Trying to get property of non-object
How can I get any specific value separetly using foreach()?

Try this :
<?php
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
$images = get_images("porsche");
//print_r($images);
foreach ($images['responseData']['results'] as $result) {
echo $result['url']. "<br>";
}
?>
Output
http://upload.wikimedia.org/wikipedia/commons/e/e7/2012_NAIAS_Red_Porsche_991_convertible_(world_premiere).jpg
http://www.inautonews.com/wp-content/uploads/2012/05/porsche-911-club-coupe-1.jpg
http://o.aolcdn.com/hss/storage/adam/6e58b30fb96bf0d28d10fa6d290682e7/porsche-exclusive-911t-cab.jpg
http://media.caranddriver.com/images/media/510773/porsche-960-updated-inline-photo-514518-s-original.jpg

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

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

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.

Quick q. Mailchimp API 3.0

Can i use the first script or i need to use the curl option for mailchimp 3.0? I read some posts that the first one may be depreciated.. is that correct? Note that i'm not running on WordPress. Thank you for your fast answers.
<?php
require("vendor/autoload.php");
use \DrewM\MailChimp\MailChimp;
$mc = new MailChimp('apikey');
$email = $_POST['email'];
$subscriber_hash = $mc->subscriberHash($email);
$response = [];
$list_id = 'listid';
$resp = $mc->get("/lists/$list_id/members/$subscriber_hash";
if ($mc->success()) {
$response['message'] = 'Thank you for subscribing to the mailing list';
// User successfully subscribed - set HTTP status code to 200
http_response_code(200);
} else {
$response['message'] = $mc->getLastError();
// User not subscribed - set HTTP status code to 400
http_response_code(400);
}
// Return json-formatted response
echo json_encode($response);
?>
Or should i use this one?
function mc_checklist($email, $debug, $apikey, $listid, $server) {
$userid = md5($email);
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$server.'.api.mailchimp.com/3.0/lists/'.$listid.'/members/' . $userid);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '. $auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$result = curl_exec($ch);
if ($debug) {
var_dump($result);
}
$json = json_decode($result);
echo $json->{'status'};
}
This row is only for stackoverflow not alowing me to post that much code without including more details.
The first is not deprecated. It uses this wrapper to make API calls using the same API version that the second block of code uses. It's just simpler to work with so you don't have to write separate CURL requests for every call. You can also take a look at some of its source code and notice that it uses CURL anyway to make its calls.
So either way will use CURL, and whichever option you choose is simply a matter of preference.
Hopefully that clears it up for you!

The resource doesn't support specified Http Verb

I am trying to make a contact form for a static website hosted in an Azure blob.
When I click submit I can see the following error in the Console.
Failed to load resource: the server responded with a status of 405
(The resource doesn't support specified Http Verb.)
I think the issue may be that I need to set up CORS for mailgun.
However I don't know what values to put
Here is send.php code
<?php
if( isset($_POST) ){
$postData = $_POST;
$mailgun = sendMailgun($postData);
if($mailgun) {
echo "Great success.";
} else {
echo "Mailgun did not connect properly.";
}
}
function sendMailgun($data) {
$api_key = 'INSERT_API_KEY_HERE';
$api_domain = 'INSERT_DOMAIN_HERE';
$send_to = 'YOUR_EMAIL';
// sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
// form data
$postcontent = $data['data'];
$reply = $data['senderAddress'];
$messageBody = "<p>You have received a new message from the contact form on your website.</p>
{$postcontent}
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
$config = array();
$config['api_key'] = $api_key;
$config['api_url'] = 'https://api.mailgun.net/v3/'.$api_domain.'/messages';
$message = array();
$message['from'] = $reply;
$message['to'] = $send_to;
$message['h:Reply-To'] = $reply;
$message['subject'] = "New Message from your Mailgun Contact Form";
$message['html'] = $messageBody;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config['api_url']);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:{$config['api_key']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,$message);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
?>
This question is a follow up from this question
I have tried including the subdomain www in the api_domain.
PHP does not run client side which means it is not suitable for a static website. As mentioned in this question
Alternatives are mentioned here

How to Redirect a login request to an external domain using PHP (Using Laravel 4)

I have two webs (Client side and Admin side) but are independent, I mean are in different domains but both using the same DB. I want to allow the Admins to login from Client side but once I recognize that isn't a normal user I want to redirect the login request to the other web and parse everything from the Admin side, just if I was trying to login from the admin web.
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$message = "Wrong Data";
try {
if(Auth::attempt($credentials)) {
if(Auth::user()->role_id < 4) {
$url = 'http://externaldomain.info/login';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
return $response;
}
return Redirect::to('/');
}
} catch( \Toddish\Verify\UserNotFoundException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserUnverifiedException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserDisabledException $e ) {
$message = _("User disabled");
}
Instead of the dashboard I get the login screen, I checked it with fiddler and didn't see any post request to the external domain, I just saw the login page request(GET).
EDIT
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$message = "Wrong Data";
try {
if(Auth::attempt($credentials)) {
if(Auth::user()->role_id < 4) {
$url = 'http://externaldomain.info/login';
$html = new \Htmldom($url);
$token = "";
foreach($html->find('input') as $element) {
if($element->name == "_token") {
$token = $element->value;
}
}
$credentials['_token'] = $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
return $response;
}
return Redirect::to('/');
}
} catch( \Toddish\Verify\UserNotFoundException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserUnverifiedException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserDisabledException $e ) {
$message = _("User disabled");
}
I'm using "yangqi/htmldom": "dev-master" to get the "_token", but I can't see the Request in fiddler, it keeps redirecting me to the login page instead of the dashboard.
It's probably because you forgot to add "_token" and "remember" fields.
The post you need to make should contain those for default login panel:
_token JB6nC85wLkFQtTglpiuoWk06YxI3Jx3no0xVQx0K
email admin#blabala.com
password 123456
remember on
Token is created by Laravel automatically for protecting your application from CSRF attacks.
You have two ways, first make request to your login page scrap the token. Then make a second request for post with that token.
Second you can disable the token for login page.
Ok, after your edit missing thing to do adding COOKIEJAR in curl request. Your current request is working like a browser with cookies disabled.
$url = 'http://externaldomain.info/login';
$file = "cookiefile.txt";
$fp = #fopen($file, "x");
if($fp)
fclose($fp);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_token = curl_exec ($ch);
curl_close ($ch);
$html = new \Htmldom();
// Load HTML from a string
$html->load($response_token);
$token = "";
foreach($html->find('input') as $element) {
if($element->name == "_token") {
$token = $element->value;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
BTW, your first request to page should also need to use same cookie file. I suggest you to use curl for making the first request too.

Resources