I'm tyring to use curl to print a return from a url. The code I have so far looks like this:
<?php
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
$query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$url_final = $url.''.$url_query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
the only obvious problem I know of it that the server being queried uses GET instead of POST. Are there GET alternatives to this method?
curl_setopt($ch, CURLOPT_POST, 0);
Curl uses GET by default. You were setting it to POST. You can override it if you ever need to with curl_setopt($ch, CURLOPT_HTTPGET, 1);
Use file_get_contents() function
file_get_contents
Or curl_setopt($ch, CURLOPT_HTTPGET, 1);
use
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
All these years and nobody's given the right answer; the way to build a query string is to use http_build_query() with an array. This automatically escapes everything and returns a simple string.
$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
"eligibilityType" => "Property",
"requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";
You are missing a question mark in the URL.
Should be like:
$query = '?eligibilityType=Property&...';
Also, that XML in your URL needs encoding, e.g. use the urlencode() function in PHP.
Related
I have used curl in php and set parameter in "CURLOPT_POSTFIELDS". And I use return $_REQUEST/$_POST on the target url for checking my passed parameter are posted correctly. But I am not able to check the posted parameter in target page.
Example of target url:- http://www.eg.com/target
curl_setopt($ipnexec, CURLOPT_URL, "http://www.eg.com/target");
CODE
$clientId = "AXLAatA9ucEkGt2C9y5SuNRd24Ys4NPod8VJmNNFq5otso1RQRIn";
$secret = "EGOojWJihcU8wnGTVQivKOsD_ylB5mMdaWmbn_1UWGlqbaugSCOZ";
$post = array(
"key" => $clientId,
"secret" => $secret
);
$ipnexec = curl_init();
curl_setopt($ipnexec, CURLOPT_URL, "http://www.eg.com/target");
curl_setopt($ipnexec, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ipnexec, CURLOPT_POST, true);
curl_setopt($ipnexec, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ipnexec, CURLOPT_RETURNTRANSFER, true);
$ipnresult = curl_exec($ipnexec);
$result = json_decode($ipnresult);
Any helps !!
Regards
Patrick
If you do have access to the endpoint at http://www.eg.com/target, you need to change the stream used. $_REQUEST is for form encoded data only. To access raw json, you need to use
$data = file_get_contents('php://input');
And then if you want to "overwrite $_POST, use
$_POST = json_decode($data, true);
I am currently using the following code:
<?php
/* Pre-requisite: Download the required PHP OAuth class from http://oauth.googlecode.com/svn/code/php/OAuth.php. This is used below */
require("OAuth.php");
$url = "https://yboss.yahooapis.com/geo/placespotter";
$cc_key = "MY_KEY";
$cc_secret = "MY_SECRET";
$text = "EYES ON LONDON Electric night in 100-meter dash";
$args = array();
$args["documentType"] = urlencode("text/plain");
$args["documentContent"] = urlencode($text);
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"POST", $url,$args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());//.',Content-Length: '.strlen($text));
//print_r($headers.',Content-Length: '.strlen($text));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// somehow this line is not solving the issue
// curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Length:'.strlen($text)));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
print_r($rsp);
//echo "======= ENDING";
?>
With my own access keys and all, with the OAuth.php library.
Somehow I kept getting a Content-Length undefined error.
If I were to attempt to define Content-Length like this ( based on some answers seen here on StackOverFlow:
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Length:'.strlen($text)));
I do not get any response.
May I know how can this issue be solved?
Thanks!
PS: the php example comes from the official example: https://gist.github.com/ydn/bcf8b301125c8ffa986f#file-placespotter-php
LATEST EDIT
I've updated my code based on #alexblex's comment
<?php
/* Pre-requisite: Download the required PHP OAuth class from http://oauth.googlecode.com/svn/code/php/OAuth.php. This is used below */
require("OAuth.php");
$url = "https://yboss.yahooapis.com/geo/placespotter";
$cc_key = "MY_KEY";
$cc_secret = "MY_SECRET";
$text = "EYES ON LONDON Electric from Singapore Raffles Place";
$args = array();
$args["documentType"] = urlencode("text/plain");
$args["documentContent"] = urlencode($text);
$args["outputType"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"PUT", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());//.',Content-Length: '.strlen($text));
//$headers = array($request->to_header().',Content-Length="'.strlen($text).'"');
//$headers = array($request->to_header().',Content-Length: 277');
print_r($headers);
//print_r($headers.',Content-Length: '.strlen($text));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request->to_postdata());
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
echo "\n\n\n\n";
var_dump($rsp);
//print_r($rsp);
?>
Currently, this new code returns a
{"bossresponse":{"responsecode":"500","reason":"non 200 status code
from backend: 415"}
error.
You send no POST data, hence no Content-Length being sent. To make a correct curl request you need to specify which data you like to send. In your case it is likely to be:
curl_setopt($ch, CURLOPT_POSTFIELDS, $request->to_postdata());
IF it should be a POST request. The PlaceSpotter docs reads:
The PlaceSpotter Web service supports only the HTTP PUT method. Other HTTP methods are not supported.
So I assume it should be PUT method instead:
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"PUT", $url,$args);
....
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
EDIT for 415 response code
It may be an issue with double urlencodeing.
Try to set arguments as unencoded text:
$args["documentType"] = "text/plain";
$args["documentContent"] = $text;
As per RFC-2616 Content-Type header indicates the size of the entity-body without headers. So if you would like to make POST requests without entity-body you should specify Content-Length: 0. Give this a try.
I have a little problem. My code:
<?php
$url = "http://xxxx/duplicate";
$data = array (
userId => xxxx, // authentication userId
loginToken => 'xxxx', // authentication loginToken
"id" => "123456",
'section' => 'LotRental',
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
echo json_encode($data_string);
?>
but it creates this post:
userId=xxxx&loginToken=xxxx&id=123456§ion=LotRental
it changes "section" to "§ion"
request shoud look like:
userId=xxxx&loginToken=xxxx&id=123456§ion=LotRental
how to fix it?
Thanks
update:
I can duplicate my item by two ways: this curl above or just type url in browser
when I execute my php script I'm getting error from a serwer:
HTTP ERROR: 405
METHOD_NOT_ALLOWED
RequestURI=xxxx/duplicate.dispatch
But when I type in browser
http://xxxx/duplicate?userId=xxxx&loginToken=xxxx&id=123456§ion=LotRental
it works fine
The script itself is OK wrt. to its output. It looks like you're viewing the output of this script in a browser. You must then properly HTML-encode the output before sending it to the browser, but instead you seem to JSON-encode it. So instead of:
echo json_encode($data_string);
you would use:
echo htmlentities($data_string);
For testing where should i give the url of the site, can you show me with the example in the above code?
$r = new HTTPRequest("server.php", HTTP_METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
$r->send();
var_dump($r->getResponseCode());
var_dump($r->getResponseBody());
Simply use addHeaders().
The XMLHttpRequest is the value of the X-Requested-With header, so you just have to do:
$r = new HTTPRequest("http://mywebservices.com/somewebserver.php", HTTP_METH_POST);
$r->addHeaders(array('X-Requested-With' => 'XMLHttpRequest'));
Instructions for installing HTTP from PECL: http://www.php.net/manual/en/http.setup.php
phpdev has answered your question very well, and if you install the HTTP extension and do it as according to the answer it will surely work.
$r = new HttpRequest('http://your-required-url-here', HttpRequest::METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
echo $r->send()->getBody();
The urls given by you in the previous comments are not well formed, it seems that you have pasted some random URL.
This is just another way to do it with php CURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.openfirms.com/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array('omg' => 'wtf');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_R($output);
This will output the contents of specified url. Hope it will help
Ruby Code:
# Turn hash input into JSON, store it in variable called "my_input"
my_input = { "itemFilter" => { "keywords" => "milk" }}.to_json
# Open connection to website.com
#http = Net::HTTP.new("website.com")
# Post the request to our API, with the "findItems" name and our JSON from above as the value
response_code, data = #http.post("/requests", "findItems=#{my_input}",
{'X-CUSTOM-HEADER' => 'MYCUSTOMCODE'})
my_hash = Crack::JSON.parse(data)
my_milk = my_hash["findItems"]["item"].first
PHP code:
$requestBody = json_encode(array("itemFilter" => array( "keywords" => "milk" )));
$headers = array ('X-CUSTOM-HEADER: MYCODE');
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, 'website.com/request/findItems=');
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
print_r($response);
Take a look at json_encode, json_decode and the cURL extension.
Found the problem.. Thanks for the input. I put a trailing slash where it was not required, and the json_encode was putting brackets around the encoding, and it didn't need them.