I'm getting an empty response from BLS for a request to their API. Also, $http_response_header is empty.
Why would the $http_response_header be empty? When trying via http instead of https, the response header at least shows the 301 redirect
$url = 'https://api.bls.gov/publicAPI/v2/timeseries/data/';
$method = 'POST';
$query = array(
'seriesid' => array('CUSR0000SA0'),
"registrationkey" => "XXXXXX" ,
'startyear' => '2016',
'endyear' => '2018'
);
$pd = json_encode($query);
$contentType = 'Content-Type: application/json';
$contentLength = 'Content-Length: ' . strlen($pd);
$result = file_get_contents(
$url, null, stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => $contentType . "\r\n" . $contentLength . "\r\n",
'content' => $pd ),
"ssl"=>array(
"cafile" => "C:/xampp/php/cacert.pem",
"verify_peer"=> true,
"verify_peer_name"=> true,
),
)
)
);
var_dump($http_response_header);
var_dump($result);
output:
array(0) { } string(0) ""
I ended up trying curl instead and used the following to output the error. The server was responding with an unknown SSL version because I am using an old version of PHP. I upgraded my xampp and now I'm getting the expected results.
$fp = fopen('/errorlog.txt', 'w');
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
Related
I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
I've started making a webpage that uses an API from another website to get phone numbers for verification of websites, which I've gotten working with Python already. However, when I try to use cURL to get the JSON data from the API it returns nothing. The code for the PHP is below.
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$params = array(
'metod' => 'get_number', # misspelt because it is not an english website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX',
);
$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}
curl_close($ch);
print_r($result);`
I expect that when the code is executed on the server it should give all of the JSON from the file, which I can then use later to pick out only certain parts of it to use elsewhere. However the actual results are that it does not print anything, as seen here: https://imgur.com/sdCYhlw
I'm not sure why your code doesn't work, but a simpler alternative could be to use file_get_contents:
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$postdata = http_build_query(
array(
'metod' => 'get_number', # misspelled because it is not an English website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX'
)
);
$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($url, false, $context);
print_r($result);
I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
I am trying to use gcm in appengine using PHP runtime. Following is the code, which uses URLFetch service
$context = array("https"=>
array( "method" => "post",
"content" => json_encode($fields),
"header" => "Content-Type: application/json\r\n" .
"Authorization: key=" . GOOGLE_API_KEY . "\r\n"
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
Following is the Original code that uses PHP Curl:
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
PHP code that uses Curl works well, but the code that uses urlfetch service of appengine does't work. Can someone tell me where am I doing wrong.
This is tested code.
public function sendAndroidPushNotification($registration_ids, $message)
{
// Adding devicetoken in array
$registrationIds = array($registration_ids);
$msg = array(
'message' => $message,
'title' => 'notification center',
'tickerText' => $message,
'vibrate' => 1,
'sound' => 1,
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$fields = json_encode($fields);
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
'Authorization: key = '. "\r\n" .
'Content-Type: application/json'. "\r\n",
"content" => $fields,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
),
);
$arrContextOptions = stream_context_create($arrContextOptions);
$result = file_get_contents('https://android.googleapis.com/gcm/send', false, $arrContextOptions);
return $result;
}
I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.