posting json data with curl and failing - php

I have this function here:
public static function call($action, array $args)
{
$post_args = array(
'action' => $action,
'args' => $args
);
$stream = json_encode($post_args);
$headers = array(
'Content-type: application/json',
'Accept: application/json',
'Expect:'
);
$userpwd = self::$_user.':'.sha1(sha1(self::$_pass));
$ch = curl_init();
$args = array(
CURLOPT_URL => self::$_url,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $stream,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => $userpwd
);
curl_setopt_array($ch, $args);
$res = curl_exec($ch);
$data = json_decode($res, true);
if (isset($data) === TRUE
&& empty($data) === FALSE
) {
$res = $data;
}
return $res;
}//end call()
and at the URL where I'm posting, I'm just doing:
echo file_get_contents('php://input');
but getting nothing, even though I do post data. What could be the problem? I'm at a dead end.
Also, why do I need CURLOPT_FOLLOWLOCATION set to TRUE when I'm just posting to a simple virtual host URL on my local machine, not doing any redirects.
EDIT:
tried redoing it with fopen like so:
public static function call($action, array $args)
{
$post_args = array(
'action' => $action,
'args' => $args
);
$stream = json_encode($post_args);
$userpwd = self::$_user.':'.sha1(sha1(self::$_pass));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array(
"Authorization: Basic ".base64_encode($userpwd),
"Content-type: application/json"
),
'content' => $stream
)
);
$context = stream_context_create($opts);
$res = '';
$fp = fopen(self::$_url, 'r', false, $context);
if($fp){
while (!feof($fp)){
$res .= fread($fp, 128);
}
}
return $res;
}//end call()
no success. The connection works with curl and with fopen, since I pass the status along with result (which is just the php://input stream). Any ideas?

Can you be sure about that curl_exec function ends successfully. Also, why don't you use fopen for this purpose. I have written a JSON RPC client and server. I'm sending requests with fopen, and it works perfect.
$httpRequestOptions =
array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-type: application/json',
'content'=>$requestJSON
)
);
$context = stream_context_create($httpRequestOptions);
// send request
if($fileHandler = #fopen($serverURL, 'r', false, $context)){
I'm not writing the rest. You can use this code I have written.

Found out the problem.
I was calling http://localhost/api, since I thought that it would load the index.php automatically, and then I was going to change the default file name for the folder.
The problem was that I didn't add index.php at the end - I should've called http://localhost/api/index.php.
This way it worked with cURL and with fopen.
Any ideas how to call the API without revealing the filename?

Related

PHP: Using file_get_contents to access an API - Empty Response

Sorry for the messy code in advance. I want to write a code which returns me infos from the official Blizzard API, which I can then print out on my homepage. The code doesn't throw any errors but it doesn't print out something either. For Starters:
I would also prefer using CURL, but my homepage is on a Wordpress Hosting Site and I don't know how to install the CURL Library that way
allow_furl_open is on
$url = "https://eu.battle.net/oauth/token";
$data = array('grant_type' => 'client_credentials');
//HTTP options
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array ('Content-type: multipart/form-data', 'Authorization: Basic ' .
base64_encode("$client_id:$client_pass")),
'content' => json_encode($data)
)
);
//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
$accessToken = $json['access_token'];
$tokenURL = "https://us.api.blizzard.com/data/wow/token/?namespace=dynamic-eu";
$opts2 = array('http' =>
array(
'method' => 'POST',
'header' => array('Content-type: multipart/form-data', 'Authorization: Bearer ' . $accessToken),
)
);
$context2 = stream_context_create($opts2);
$json2 = file_get_contents($tokenURL,false,$context2);
$result2 = json_decode($json2, true);
$tokenprice = $result2['price'];
echo "<p>Tokenpreis:" .$tokenprice. "</p>";
I didn't add the $client_id and $client_pass into the code snippet, but this exists obviously. I used this PHP CURL Snippet as template. And this is a short explanation on blizzard's site on how is this supposed to work:
Anyone got any ideas what went wrong? I am really out of ideas here and would love anyone who could help.
Thanks in advance
Based on the curl example from the linked API docs, the content type should be application/x-www-form-urlencoded, and so for the initial request to https://eu.battle.net/oauth/token you should be able to follow the example here.
In your case this will look something like:
$url = 'https://eu.battle.net/oauth/token';
$data = array('grant_type' => 'client_credentials');
$opts = array(
'http' => array(
'method' => 'POST',
'header' => array (
'Content-type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode("$client_id:$client_pass")
),
'content' => http_build_query($data)
)
);
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
Also, in your code you are storing the raw result from the initial request in $json, then the decoded array in $result, but attempting to get the access_token from the initial request, instead of the decoded array.

PHP sends GET instead of POST

I have to post some data, but the same adress have some GET and POST functions. My PHP is sending a GET instead of a POST.
$apiURL = 'https://myAPI.com.br/api';
$data = http_build_query(array('postdata' => 10));
$uriRequest = $apiURL.'/main';
$options = array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
'https' => array(
'header' => 'Content-type: application/x-www-form-urlencoded',
'method' => 'POST',
'content' => $data
),
);
$context = stream_context_create($options);
$result = file_get_contents($uriRequest, false, $context);
if ($result === FALSE) {
return var_dump($result);
}
return var_dump($result);
I know the ssl part it isnt safe, but it is just for prototyping purpose.
I cant get PHP to POST intestead of GET on the adress 'https://myAPI.com.br/api/main'.
Judging from http://php.net/manual/de/function.stream-context-create.php#74795 the correct way to create a stream context for a https secured page is:
<?php
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
As you can see we are using 'http' => array... instead of https.

Google Short URL API: Forbidden

I have what I think is correctly written code yet whenever I try and call it I'm getting permission denied from Google.
file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
This isn't a rate limit or anything as I currently have zero ever used...
I would have thought this is due to an incorrect API key but I've tried resetting it a number of times. There isn't some downtime while the API is first applied is there?
Or am I missing a header setting or something else just as small?
public function getShortUrl()
{
$longUrl = "http://example.com/";
$apiKey = "MY REAL KEY IS HERE";
$opts = array(
'http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json",
'content' => json_encode(array(
'longUrl' => $longUrl,
'key' => $apiKey
))
)
);
$context = stream_context_create($opts);
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url", false, $context);
//decode the returned JSON object
return json_decode($result, true);
}
It seems I need to manually specify the key in the URL
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url?key=" . $apiKey, false, $context);
This now works. There must be something funny with how the API inspects POST for the key (or lack of doing so).
Edit: For anyone in the future this is my complete function
public static function getShortUrl($link = "http://example.com")
{
define("API_BASE_URL", "https://www.googleapis.com/urlshortener/v1/url?");
define("API_KEY", "PUT YOUR KEY HERE");
// Used for file_get_contents
$fileOpts = array(
'key' => API_KEY,
'fields' => 'id' // We want ONLY the short URL
);
// Used for stream_context_create
$streamOpts = array(
'http' =>
array(
'method' => 'POST',
'header' => [
"Content-type: application/json",
],
'content' => json_encode(array(
'longUrl' => $link,
))
)
);
$context = stream_context_create($streamOpts);
$result = file_get_contents(API_BASE_URL . http_build_query($fileOpts), false, $context);
return json_decode($result, false)->id;
}

How do I send files in PHP via CURL? #filename won't work

I'm trying to send an image via POST using PHP's CURL methods.
I am sending the image to an API that expects the POST field 'photo_file' to be an image.
I set the 'photo_file' to # followed by the file name.
However, when I make the request the API receives the literal string '#filename' instead of the file contents.
Here is the relevant code:
Calling code:
$data = array(
'campaign_id' => $_POST['campaign_id'],
);
$img_source = realpath($img_source); // "/Users/andrew/Sites/roo/9699d27bb09fda3133701ca9af084e3d.jpg"
$response = $y->upload_photo($img_source, $data);
$y->upload_photo():
public function upload_photo($img_source, $data) {
$fields = array(
'campaign_id' => $data['campaign_id'],
'photo_file' => '#' . $img_source
);
return $this->request('photos', $fields, 'post');
}
$this->request() (relevant parts):
public function request($function, $fields = array(), $method = 'get') {
$ch = curl_init();
$url = $this->host . $function;
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Accept: application/json', 'Expect:'),
CURLOPT_VERBOSE => 1,
CURLOPT_HEADER => 1,
);
if ($method == 'post') {
$curlConfig[CURLOPT_POST] = 1;
$curlConfig[CURLOPT_POSTFIELDS] = true;
$curlConfig[CURLOPT_POSTFIELDS] = $fields;
}
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
list($header_blob, $body) = explode("\r\n\r\n", $result, 3);
$this->http_status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return json_decode($body);
}
The API is returning an error, and when its dev looked at the logs he saw that the request on his end was:
'campaign_id' => '4'
'photo_file' => '#/Users/andrew/Sites/roo/9699d27bb09fda3133701ca9af084e3d.jpg'
so adding # to the beginning of the file didn't actually send the contents of the file, like I understand it's supposed to. Also, the API works fine with other platforms that use it, so the problem is definitely on my end.

POST xml WITHOUT using CURL

I need to POST xml data without CuRL.
there are a LOT of snippets, but nothing seems to work.
The latest attempt:
function salesOrder($xml, $url)
{
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/xml\r\n",
'content' => $xml,
'timeout' => 5,
),
));
$ret = file_get_contents($url, false, $context);
return false !== $ret;
}
returns nothing, blank page.
I have tried http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
The problem is I dont really understand it and i can not seem to find a good tutorial that covers this problem. Can anyone point me in the right direction?
You can use this to achieve that
$xml = "<xml><name>hello</name></xml>" ;
$opts = array (
'http' => array (
'method' => "POST",
'content' => $xml,
'timeout' => 5,
'header' => "Content-Type: text/xml; charset=utf-8"
)
);
$context = stream_context_create ( $opts );
$fp = fopen ( 'http://example.com/b.php', 'r', false, $context );
fpassthru ( $fp );
fclose ( $fp );
http://example.com/b.php
file_put_contents("php://output", file_get_contents("php://input"));

Categories