I need to send data to an API using PHP. The API has a redirect page before showing the final result. The following code shows the content of the redirecting page rather than the final result. How can I wait until the final result?
$url = 'https://example.com/api';
$data = array('text' => "try");
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
echo $result;
P.S. I got this code from one of stackoverflow's questions.
You could use cURL to get the final response, using CURLOPT_FOLLOWLOCATION:
From documentation :
CURLOPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
$url = 'https://example.com/api';
$data = array('text' => "try");
$full_url = $url . (strpos($url, '?') === FALSE ? '?' : '')
. http_build_query($data) ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
var_dump($response) ;
Related
public function auth_callback()
{
if ($this->input->get("code") != null)
{
$this->Strava_model->UpdateProfileStravaToken($this->input->get("code"),$this->session->userdata("athlete_id"));
$url = "http://www.strava.com/oauth/token?client_id=[xxxxx]&client_secret=[xxxxxxxxxxx]&code=".$this->input->get("code")."&grant_type=authorization_code";
$post = array();
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($post)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
echo $result;exit;
$cURLConnection = curl_init($url);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $post);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);
$jsonArrayResponse = json_decode($apiResponse);
redirect($this->config->item("base_url") . "/activity");
}
}
I manage to get the code, and now proceed to get access token.
I'm using php curl to send post as below:
http://www.strava.com/oauth/token?client_id=[xxxx]&client_secret=[xxxxx]&code=[code retrieve from redirection]&grant_type=authorization_code
Once I executed the code above, I got this "You're being redirect..."
Can anyone advice and help?
Generally requests to the OAuth2 token endpoint require parameters to be passed as form-data, in the request body. Based on your current source, you are sending an empty request body.
I am trying to create a service on hook.io to load token from another API.
public function loadToken()
{
$computedHash = base64_encode(hash_hmac ( 'md5' , $this->authServiceUrl , $this->password, true ));
$authorization = 'Authorization: Bearer '.$this->username.':'.$computedHash;
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, '');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($curl, CURLOPT_URL, $this->authServiceUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$obj = json_decode($result);
$info = curl_getinfo($curl);
curl_close($curl);
if($info['http_code'] != '200')
{
// print error from the server
echo($obj);
return NULL;
}
return $obj;
}
But it turns out hook.io doesn't support cUrl in PHP . I know it can done directly with php but i don't know how.
edit :
i used file_get_contents now it's give some other error now.
$username = '';
$password = '';
$authServiceUrl = '';
$computedHash = base64_encode(hash_hmac ( 'md5' , $authServiceUrl , $password, true ));
$authorization = 'Authorization: Bearer '.$username.':'.$computedHash;
// Create map with request parameters
// Build Http query using params
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Content-Type: application/json". $authorization ,
);
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
$authServiceUrl, // page url
false,
$context);
I have added the error in comments below
Actually, hook.io has curl support as far as I know. But if you want to try other alternatives, you can use file_get_contents. It has support for custom context and parameters.
$opts = [
'http' => [
'method' => 'POST',
'headers' => ['Authorization' => 'Bearer ' . $this->username . ':' . $computedHash]
]
];
$context = stream_context_create($opts);
$file = file_get_contents('http://www.hook.io/example/', false, $context);
I am trying to learn how to interact with the unofficial xbox api (xboxapi.com) but I can't seem to figure out how to use it. The documentation is very scarce. This is my most recent (and what i thought best) attempt.
<?php
$gamertag = rawurlencode("Major Nelson");
$ch = curl_init("http://www.xboxapi.com/v2/xuid/" . $gamertag);
$headers = array('X-Auth: InsertAuthCodeHere', 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers ); # custom headers, see above
$xuid = curl_exec( $ch ); # run!
curl_close($ch);
echo $xuid;
?>
Upon running the above I get "301 Moved Permanently". Can anyone see what i am doing wrong? Thanks.
You need to replace xuid with your actual xbox profile user id.
Additionally replace InsertAuthCodeHere with your API auth code.
You can find both on your xboxapi account profile after logging into xbox live.
See: https://xboxapi.com/v2/2533274813081462/xboxonegames
Update - Guzzle
I was able to get it working with Guzzle, works with http or https
require __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php'; //defines XboxAPI_Key
$gamertag = isset($_GET['gamertag']) ? urldecode($_GET['gamertag']) : 'Major Nelson';
$url = 'http://xboxapi.com/v2/xuid/' . rawurlencode($gamertag);
$guzzle = new GuzzleHttp\Client();
$response = $guzzle->get($url, [
'headers' => [
'X-Auth' => XboxAPI_Key,
'Content-Type' => 'application/json'
],
]);
echo $response->getBody(); //2584878536129841
Update 2 - cURL
The issue is related to validating the SSL certificate via CURLOPT_SSL_VERIFYPEER => false and the redirect from http://www. to https:// occurring which is enabled with CURLOPT_FOLLOWLOCATION => true
require_once __DIR__ . '/config.php';
$gamertag = isset($_GET['gamertag']) ? urldecode($_GET['gamertag']) : 'Major Nelson';
$url = 'http://www.xboxapi.com/v2/xuid/' . rawurlencode($gamertag);
/**
* proper url for no redirects
* $url = 'https://xboxapi.com/v2/xuid/' . rawurlencode($gamertag);
*/
$options = [
CURLOPT_RETURNTRANSFER => true, // return variable
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_SSL_VERIFYPEER => false, //do not verify SSL cert
CURLOPT_HTTPHEADER => [
'X-Auth: ' . XboxAPI_Key
]
];
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
echo $content; //2584878536129841
I got an answer. We were missing required curly braces. Working code:
$gamertag = rawurlencode("Major Nelson");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://xboxapi.com/v2/xuid/{$gamertag}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"X-Auth: InsertAuthCode",
]);
$output = curl_exec($ch);
curl_close ($ch);
print $output;
I have made a custom status and test if it is 2 and on that basis am trying to delete the main image of a product. At first I didn't know that cURL needs special treatment if working with sessions and I got redirected to the admin login screen. This modification is supposed to go into the file admin/controller/catalog/product (using VQMod of course). Only now I'm getting NULL for response.
if((int) $this->request->post['status'] == 2) {
if(isset($this->request->post['image'])) {
$params = array(
'path' => $this->request->post['image']
);
$defaults = array(
CURLOPT_URL => $this->url->link('common/filemanager/delete', 'token=' . $this->session->data['token'], 'SSL'),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEJAR => 'cookie-jar',
CURLOPT_COOKIEFILE => '/home/u32807/tmp'
);
$ch = curl_init();
curl_setopt_array($ch, $defaults);
$ouput = curl_exec($ch);
if($output === false) {
echo 'Curl error: ' . curl_error($ch);
die();
}
else {
var_dump($output);
die();
}
}
}
I tried commenting out CURLOPT_POSTFIELDS and also I tried feeding it an empty array, but still NULL. There must thus be something wrong with the way I have set up the connection but I do not know where to start to debug it. Hewp pweeze! :/ OpenCart version is 1.5.6.4.
you need to add one more portion for curl,i.e
CURLOPT_CUSTOMREQUEST=> 'DELETE',
check my function for delete:
public function curl_delete_function($mypath, $json='')
{
$url =$this->__url.$mypath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
I have a form on one page with the action set to /process.php
Within the process.php I have the validation of the form and also it writes to a database on the server it sits on.
What I'd like to do after it has written to the database, is post the variables to another domain that will then process those variables differently.
Example using curl:
$name = 'Test';
$email = 'test#gmail.com';
$ch = curl_init(); // initialize curl handle
$url = "http://domain2.com/process.php";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // times out after 10s
curl_setopt($ch, CURLOPT_POST, 1); // set POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, "text=$name&name=$email"); // post fields
$data = curl_exec($ch); // run the whole process
curl_close($ch);
Example without curl: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
you can use file_get_contents for the same.
Example:
$name="foobar";
$messge="blabla";
$postdata = http_build_query(
array(
'name' => $name,
'message' => $message
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = #file_get_contents('http://yourdomain.com/process_request.php', false, $context);
if($http_response_header[0]=="HTTP/1.1 404 Not Found"):
echo "iam 404";
elseif($http_response_header[0]=="HTTP/1.1 200 OK"):
echo "iam 200";
else:
echo "unknown error";
endif;