Using CURL to use json's GET using PHP - php

I am very new to PHP and have done some research on how to call the json's GET function using CURL but there is something I am not doing correctly. Maybe someone can point me in the right direction. I hope I can communicate it properly. Thanks.
In my browser, when I type:
https://myWebSite.com/api/v1/people/26.json?
my browser returns a person with the ID of 26 and all their fields associated with them.
I am now trying to do this call in a PHP file. This is what I have:
//jSON URL which should be requested
$json_url = 'https://myWebSite.com';
$username = 'myUsername'; // authentication
$password = 'myPassword'; // authentication
// jSON String for request
$json_string = '/api/v1/people/26.json';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password, // authentication
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>

Try adding this to your option list:
CURLOPT_CUSTOMREQUEST => 'POST'
Edit: After re-reading the OP, it looks like there was a misunderstanding about what the request should be. If it is a GET request to a URL, it is more likely that it was supposed to go like this:
$json_string = '/api/v1/people/26.json';
$json_url = "https://myWebSite.com{$json_string}";
$username = 'myUsername'; // authentication
$password = 'myPassword'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password, // authentication
);

Related

Why does this PHP cUrl not apply the correct authentication header?

I am trying to use the files.com API here. I cannot get it to authenticate. The response I keep getting is 'bool(false)'
I need to add an api key to my header. Using PHP I have attempted this:
<?php
$key = '1234567890';
$domain = 'myDomain';
$url ="https://$domain.files.com/api/rest/v1/users.json";
$auth=['X-FilesAPI-Key'=> $key];
$ch = curl_init();
curl_setopt_array($ch,[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $auth,
]);
$content = curl_exec($ch);
$info = curl_getinfo($ch);
any suggestions to get this working would be greatly appreciated!

Send Email with SendGrid using Web Api php

I am confused with here with $pass and $api_key
are they same, because at first $pass is assigned with password of the SendGrid's username but then api_key is assigned with $pass.
if they are same they where we would use that api_key that we generated on SendGrid?
Please Help!!!
<?php
$url = 'http://sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => 'example3#sendgrid.com',
'subject' => 'testing from curl',
'html' => 'testing body',
'text' => 'testing body',
'from' => 'example#sendgrid.com',
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// print everything out
print_r($response);
?>
There's a few issues with what you're trying to do:
You should never send an API call to sendgrid.com, only api.sendgrid.com
It looks like you're trying to use the v2 API with the Params. Since you're setting up a new script, you should use the v3 API which uses proper body JSON arguments, and is RESTful.
Instead of setting up your own script, have you looked at the SendGrid PHP Library?
For authentication in a script, you should always use an API Key, not your master username & password.
It looks like you got a really old example script for testing. Where did you get that from?

Connecting to Outbrain API using PHP

I need to connect to the Outbrain API (This is the documentation: http://docs.amplifyv01.apiary.io/#).
There's a minor example in there, but when I tried connecting to my own account I didn't manage to do so...
Can't understand if I put the wrong CURLOPT_URL or didn't write my credentials in the right form... This is my code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.outbrain.com/amplify/v0.1/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: BASIC BASE-64-ENC(USERNAME:PASSWORD)",
"OB-TOKEN-V1: MY_ACCESS_TOKEN"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
If anyone knows why it didn't worked - I'd very much appreciate it...
Also if anyone has an additional code for talking with the Outbrain API - It'll help me a lot.
Thank you!
<?php
$outbrain_user = 'xxx';
$outbrain_pass = 'xxx';
// Basic access authentication
$enc_credentials = base64_encode($outbrain_user.':'.$outbrain_pass);
$ba_authenticacion = 'Basic '.$enc_credentials;
$auth_header = array(
'Authorization: '.$ba_authenticacion
);
$outbrain_api_endpoint = 'https://api.outbrain.com/amplify/v0.1/';
// authentication
$auth_url = $outbrain_api_endpoint.'/login';
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_URL => $auth_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $auth_header
)
);
$json_access_token = curl_exec($curl);
// parsing json object to string
$token_object = json_decode($json_access_token);
$token_array = get_object_vars($token_object);
// api access_token
$access_token = $token_array['OB-TOKEN-V1'];
Basically you got a wrong syntax while parsing CURLOPT_HTTPHEADER array,
also outbrain uses a basic access authentication, you can check here for docs https://en.wikipedia.org/wiki/Basic_access_authentication.
With this code you can return the access_token from outbrain.

Unexpected JSON output on HTTP request

I am currently trying to get a simple HTTP JSON response from a website.
When I look at the page when I use Google Chrome:
{"columns":[{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"decimal","size":17,"nullable":true},{"name":"xx","dataType":"varchar","size":255,"nullable":true},{"name":"xx","dataType":"varchar","size":4,"nullable":true},{"name":"xx","dataType":"varchar","size":2,"nullable":true},{"name":"xx","dataType":"varchar","size":20,"nullable":true}],"rows":[["xxxxx","xxxx/xxxx","xxxx","Yacouba","5xx","xx","xxxxx"]]}
However when I use the following php code:
<?php
$json_url = "xxxx"; // url is something else but privacy reasons etc
// Initializing curl
$ch = curl_init();
// Configuring curl options
$options = array(
CURLOPT_URL => $json_url,
CURLOPT_POST => FALSE
);
// Setting curl options
curl_setopt_array($ch, $options);
// Getting results
$result = curl_exec($ch); // Getting jSON result string
curl_close($ch);
json_decode($result);
var_dump($result);
and then the output is as fallows:
‹ì½`I–%&/mÊ{JõJ×àt¡€`$Ø#ìÁˆÍæ’ìiG#)«*ÊeVe]f#Ìí¼÷Þ{ï½÷Þ{ï½÷º;N'÷ßÿ?\fdlöÎJÚÉž!€ªÈ?~|?"~ñGÓª\/–ÍG¾÷‹?Zf‹ü£Gͪ¦)òú÷/³I^~4úh–µÙ›ë¾ºÌêé<«éæø}°wÿþè£åº¤¦%ýÙÖëü—Œz€–Y¶ø8—U=ËëbyñûÏòIÑæëú÷¯Vù²i³l9Ïòi±ÈJx÷Á&ü´E°iëŒÞÕyóû¯¦¿ÿ²n6CÛ¿=¬²½ ØÞmFXçeÖ9¡v°´ï>ª«+pÈ÷>ÚýôÓ{Ôúm±l&y}‘/ïþ>Ù´ZO2úpoow´»C¿¹ÏîïìJ?žŸÐ?;;;û÷÷?Ýûèûßÿ%ÿOÿÿzbool(true)
What could the problem be?
I fix it! :D with:
CURLOPT_ENCODING => ''

Can a PHP script reuse the same variable?

I am trying to learn PHP coming from some very basic Java experience but I am confused about variables in PHP and being reused in the same script. I have the below code which works without issue somehow even though I have multiple values for certain variables such as $url,$curl,$resp how is this working? Is it just being over written as the script executes?
<?php
$zip = $_GET["ziphtml"];
$url = "http://api.wunderground.com/api/4339efkeyf17a9/forecast10day/q/19115.json";
$curl = curl_init();
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$json_string = $resp;
$parsed_json = json_decode($json_string);
$forecastp2 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[1]->{'title'};
$forecastp3 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[2]->{'title'};
$forecastp4 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[3]->{'title'};
$forecastp5 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[4]->{'title'};
$forecastp6 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[5]->{'title'};
$forecastp7 = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'}[6]->{'title'};
$zip = $_GET["ziphtml"];
$url = "http://api.wunderground.com/api/4dgg345353vdryteyfg339ekey7a9/geolookup/conditions/q/IA/".$zip.".json";
$curl = curl_init();
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$json_string = $resp;
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'current_observation'}->{'display_location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperatdure in ${location} is: ${temp_f}\n<br /> and it is now ${forecastp2}\n<br /> and then it will be ${forecastp3}\n<br /> and then ${forecastp4}\n<br />and then ${forecastp5}\n<br />and then ${forecastp6}\n<br />and then ${forecastp7}";
?>
It is just overwritten.
Java does the same, but Java checks type, so you cannot reassign values as freely.
A variable is a name for a location in memory. When you store a new value in that location, the old value is lost and the name now refers to the new value.

Categories