(cURL / PHP) API Response - Invalid HTTP method used - php

Hopefully a simple question, I have tried to connect to my first REST API using PHP and cURL. My code is as follows:
<?php
$zooplaKey = "mykey";
$postcode = $_GET['postcode'];
$sendData = array('api_key' => $zooplaKey,
'postcode' => $postcode,
'output_type' => "postcode");
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'http://api.zoopla.co.uk/api/v1/average_area_sold_price.js');
curl_setopt($curl, CURLOPT_POSTFIELDS, $sendData);
//curl_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$raw_json = curl_exec($curl);
curl_close($curl);
$zooplaInfo = json_decode($raw_json, true);
echo "<pre>";
print_r($zooplaInfo);
echo "</pre>";
?>
Run exactly as above I get a return of:
Array
(
[error_string] => Invalid HTTP method used
[error_code] => 2
)
Uncommenting //curl_setopt($curl, CURLOPT_POST, true); or //curl_setopt($curl, CURLOPT_HTTPGET, true); just returns a blank screen.
By using the following URL I am able to get a valid result (obviously I have had to blank the api key so this link is for structure purposes only) http://api.zoopla.co.uk/api/v1/average_area_sold_price.xml?api_key=mykey&postcode=ws12dn&output_type=postcode
Thanks all.

According to the Zoopla API Documentation, what you are trying to do is to:
Retrieve the average sale price for houses in a particular area.
Retrieval is done using a GET method in the REST standard. By using CURLOPT_POSTFIELDS, cURL will automatically convert your request to a POST, which is invalid for retrieval. You should remove the post fields part, and do that instead:
curl_setopt($curl, CURLOPT_URL, 'http://full/url?'.http_build_query($sendData));

The parameters in the URL are being passed as GET. I would try appending the parameters to the CURLOPT_URL instead of putting them in the CURLOPT_POSTFIELDS array. The remote service probably requires the values be in the query string rather than being posted.

Related

how to call an api via php and get a json file from it

I want to check all of the requested urls and if the url contains "video" folder in it, redirect it to an API file. then the API gives me a json files which only contains "respond:true" or "respond:false". In case of having respond:true in the json file the url must be showed and if the json file contains respond:false a predefined simple 403 page must be showed to the user.
I know that the fist part is possible with a simple code in .htaccess file like this:
RewriteRule ^your/special/folder/ /specified/url [R,L]
But I don't know how to do the second part. I mean how to get the result of API, which is in form of a json file and check it.
You can use CURL..
GET REQUEST
$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
POST REQUEST
$postdata = array(
'name' => 'Arfan'
);
$url = "https://example.com/api/user/create";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
You can also use file_get_content to get API data.
$json = file_get_contents("$url")
You can execute second part (Calling API and response): Call API using curl and process based on its response:
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, "api_url_here");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$api_response_json = curl_exec($ch);
curl_close($ch);
//convert json to PHP array for further process
$api_response_arr = json_decode($api_response_json);
if($api_response_arr['respond'] == true ){
//code for success here
}else{
// code for false here
}
Please note: Json response from API is depend on API Response, If API is giving response in json format ( can be based on params also ).

How to get value of variable from curl in PHP?

I am working on two system.In which asterisk runs on one system-1.I want to run command in asterisk and get result back in system-2.I make curl request like below.How to get value back on system2?enter code here
exec('asterisk -rx "sip show peers"',$sip);
$POST_DATA = array(
'filename'=>$sip,
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'http://192.168.50.138/test.php');
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
$response = curl_exec($curl);
curl_close ($curl);
?>
Since you already have
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
in your code. curl_exec should already returns the content of the page instead of a BOOL.
This is a snippet of a library I use. As pointed out this might not be needed but it helped me out once...
//The content - if true, will not download the contents
curl_setopt($ch, CURLOPT_NOBODY, false);
Also it seems to have some bugs related to CURLOPT_NOBODY (which might explain why you have this issue):
http://osdir.com/ml/web.curl.general/2005-07/msg00073.html
http://curl.haxx.se/mail/curlphp-2008-03/0072.html

How to parse Curl response?

I am able to send the GET request and receive the response at following line.
$curl_resp = curl_exec($curl);
I used the following to parse the response, but it does not work, I have manually set some values to $curl_resp but still not sure how to access the value of each tag of the xml separately.
$xml = simplexml_load_string($curl_resp);
NOTE: I recevice the actual xml but cant parse it, (I need to get each tag's value separately in a variable)
Code:
<?php
$service_url = ' The Url goes here';
$curl = curl_init($service_url);
$curl_post_data = array(
"PASSWORD" => 'pass',
"USERNAME" => 'username'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_resp = curl_exec($curl);
curl_close($curl);
Your variable $curl_response is different than $curl_resp (what you're trying to parse)
You can access the value of each tag just like any other array.
if the CURLOPT_RETURNTRANSFER option is not set then your $curl_resp will just return true/false.
if it is set you may be returning false or a poorly formed xml string. If you post more code or the actual curl response text we may be able to provide more info.
EDIT:
upon reading the code looks like you are assigning the response text to $curl_response instead of $curl_resp
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "your url");
curl_setopt($ch, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

JIRA Update custom fields using REST, PHP and cURL

I am trying to update some custom fields using the REST API and PHP/cURL.
I'm wondering if I might have edited something without realizing it, while what I have below "worked" yesterday (I think), it does not work now.
I get varying responses using the different "methods", from:
I get this one using the POST method, as it is uncommented below.
HTTP 405 - The specified HTTP method is not allowed for the requested
resource ().
I get this one if I use the commented-out PUT method, with POST commented out.
{"status-code":500,"message":"Read timed out"}
And this one mixing and matching PUT and POST.
{"errorMessages":["No content to map to Object due to end of input"]}
What am I missing/doing wrong? I am using the following code:
<?php
$username = 'username';
$password = 'password';
$url = "https://example.com/rest/api/2/issue/PROJ-827";
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json'
);
$test = "This is the content of the custom field.";
$data = <<<JSON
{
"fields": {
"customfield_11334" : ["$test"]
}
}
JSON;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Also tried, with the above two lines commented out...
// curl_setopt($ch, CURLOPT_PUT, 1);
// curl_setopt($ch, CURLOPT_INFILE, $data);
// curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
echo $result;
}
curl_close($ch);
?>
The problem here is that PHP's cURL API is not particularly intuitive.
You might think that because a POST request body is sent using the following option
that a PUT request would be done the same way:
// works for sending a POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// DOES NOT work to send a PUT request
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_PUTFIELDS, $data);
Instead, to send a PUT request (with associated body data), you need the following:
// The correct way to send a PUT request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Note that even though you're sending a PUT request, you still have to use the CURLOPT_POSTFIELDS
option to send your PUT request body. It's a confusing and inconsistent process, but it's what you've
got if you want to use the PHP cURL bindings.
According to the relevant manual entrydocs, the CURLOPT_PUT option seems to only work for PUTting a file directly:
TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
A better option IMHO is to use a custom stream wrapper for HTTP client operations. This carries the
added benefit of not making your application reliant on the underlying libcurl library. Such an
implementation is beyond the scope of this question, though. Google is your friend if you're interested
in developing a stream wrapper solution.

getting results from a site using curl

I have been trying to post some variables to a site using POST method, using curl to get some results. I am posting to this link.
http://www.rasta.pk/Lhr/Lhr_Traffic.aspx
At this page you will see a drop down menu .. onchange some values are returned in "Yellow" colored table.
I have monitored this site and trying to get those results by making a post request to that link. But, I am getting "Bad Header" error. I have tried changing things but ubable to find a solution.
Here is my code:
"Canal Bank Rd",
"ScriptManager1 " => "UpdatePanelDDLRoads|DropDownRoads",
"__EVENTARGUMENT" => "",
"__EVENTTARGET" => "DropDownRoads"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerz);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, "http://www.rasta.pk/Lhr/Lhr_Traffic.aspx");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
There's too little details presented for us to know for sure.
A guess is that you're doing the wrong kind of post, since when you pass in a hash array to CURLOPT_POSTFIELDS it will do a multipart formpost which might not be what the server expects. Pass in a string instead to make a "normal" POST.
If that is not enough, use LiveHTTPHeaders or similar in a browser to figure out exactly what is sent in a "manual" session and then you make sure that your curl program mimics that operation as closely as possible.

Categories