Using postman, I send a POST to (my username and password are filled in):
https://ssl.reddit.com/api/login?api_type=json&user=XXX&passwd=XXX&rem=True
I receive a response containing a modhash and a cookie. Then, I send a second POST with postman to:
https://en.reddit.com/api/comment?api_type=json&text=7/1/15TEST&thing_id=t1_csa56v2
with the following headers (XXX has been confirmed and filled in):
User-Agent: XXX
Cookie: reddit_session=XXX
X-Modhash: XXX
This provides the correct response, but when I try to do the same thing with CURL in my PHP, it responds with USER_REQUIRED. Once again, I have confirmed that the cookie and modhash are correct.
$name = 't1_csa56v2';
$text = 'NEWEST TEST 7/2/15 12:20am';
$url = 'https://en.reddit.com/api/comment';
$modhash = 'XXX';
$cookie = 'XXX';
$headerFields = array (
'User-Agent' => 'XXX',
'Cookie' => 'reddit_session='.$cookie,
'X-Modhash' => $modhash
);
$postFields = array (
'api_type' => 'json',
'text' => $text,
'thing_id' => $name
);
$field_string = http_build_query($postFields);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, $field_string);
$response = curl_exec($ch);
What am I doing wrong? Why can't I get the same response?
Screenshot of POSTMAN:
<?php
error_reporting(E_ALL);
$name = 't1_csa56v2';
$text = 'NEWEST TEST 7/2/15 12:20am';
$url = 'https://en.reddit.com/api/comment';
$modhash = 'XXX';
$cookie = 'XXX';
$headerFields = array (
'X-Modhash' => $modhash
);
$postFields = array (
'api_type' => 'json',
'text' => $text,
'thing_id' => $name
);
$ch = curl_init($url);
assert(curl_setopt_array($ch,
array(
CURLOPT_AUTOREFERER => true,
CURLOPT_BINARYTRANSFER => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_FORBID_REUSE => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 11,
CURLOPT_ENCODING=>"",
CURLOPT_USERAGENT=>'XXX',
CURLOPT_COOKIE=>'reddit_session='.$cookie,
CURLOPT_HTTPHEADER=>$headerFields,
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>$postFields,
)));
$response = curl_exec($ch);
try this.. not sure exactly what you do wrong, but user agent should be set with CURLOPT_USERAGENT , and the cookie should be set with CURLOPT_COOKIE and you should let curl encode it for you, rather than using http_build_query
, and you should explicitly set it to a POST request, as its a GET request by default. should also enable E_ALL error reporting
Related
Hi I'm trying to setup a PHP CURL call using OAuth1 authorization method.
I've tried with POSTMAN 1st, to generate the PHP code. I've completed it with the necessary datas
<?php
$conskey = 'XXXXXXX';
$conssec = 'XXXXXXX';
$nonce = mt_rand();
$timestamp = time();
$url = 'https://some-website/api/project/subproject';
$method = 'POST';
$oauth = new OAuth($conskey, $conssec, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->setNonce($nonce);
$oauth->setTimestamp($timestamp);
$signatureOAuth = $oauth->generateSignature($method, $url);
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_URL => $url.'?oauth_consumer_key='.$conskey.
'&oauth_signature_method=HMAC-SHA1&oauth_timestamp='.$timestamp.
'&oauth_nonce='.$nonce.
'&oauth_version=1.0&oauth_signature='.$signatureOAuth,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $jsonDatas,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
// THE COOKIE I WANNA GET
'Cookie: SSESSd4f3e89d4699e1d1a071aa37eab4fcEd=DWS4UqpaykI2y7q-HJXEzGN82AKHQYnWo5hbsqkAqiQ'
),
));
$result = curl_exec($curl);
curl_close($curl);
But I've noticed that there's the cookie in the CURLOPT_HTTPHEADER entry but I don't have any idea how POSTMAN generate this cookie.
Without this cookie or with a dumb string, the CURL response is always Invalid Signature
Postman is not generating cookies for you, and neither is curl/php. you either did some prior requests (usually GET to get cookies) requests to the website where you received some cookies, or gave the cookies to postman some other way.
since you're not showing us the real url, we can only speculate, but to take an example, here is how to get a session cookie for stackoverflow.com:
<?php
$ch=curl_init();
curl_setopt_array($ch,array(
CURLOPT_COOKIEFILE => "", // setting it to empty activates the curl cookie engine (its disabled by default.),
CURLOPT_URL => "https://stackoverflow.com/",
CURLOPT_RETURNTRANSFER => true,
));
$html=curl_exec($ch);
$cookies = (function($cookielist):array{
$cookies = array();
foreach($cookielist as $cookie_raw) {
$chunks = explode("\t", $cookie_raw);
//var_dump($chunks);
$cookie['domain'] = $chunks[0];
$cookie['secure'] = $chunks[1];
$cookie['path'] = $chunks[2];
$cookie['???todo_wtf_is_this'] = $chunks[3];
$cookie['expiration'] = $chunks[4];
$cookie['name'] = $chunks[5];
$cookie['value'] = $chunks[6];
$cookies[] = $cookie;
}
return $cookies;
})(curl_getinfo($ch, CURLINFO_COOKIELIST));
var_export($cookies);
prints something like
array (
0 =>
array (
'domain' => '#HttpOnly_.stackoverflow.com',
'secure' => 'TRUE',
'path' => '/',
'???todo_wtf_is_this' => 'FALSE',
'expiration' => '2682374400',
'name' => 'prov',
'value' => '9c06f038-9f70-bee8-2a64-b095656175d1',
),
)
which could be used like
// THE COOKIE I WANNA GENERATE
'Cookie: '. $cookies[0]["name"].'='.$cookies[0]["value"]
but this is very rarely done, usually you'd just use curl's built-in cookie engine to handle cookies automatically..
I would like to verify whether someone has a valid ISIC card, I have written the following code for this Rest API (http://nakoduj.to/_upload/project_files/2015-08-18-12-51-20_DM%20-%20Integration%20Manual.pdf), but it doesn't work, and I have no idea why it doesn't.
$data = array( "cardNumber" => "S123456789000A",
"cardholderName" => "John Doe");
$data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gts-dm.orchitech.net/api/verifications');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "testdm:testdm");
$result = curl_exec($ch);
if ($result === false) {
$info = curl_getinfo($ch);
curl_close($ch);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($ch);
I'm getting false for the $result always. And there is no additional information in $info.
Thank you in advance for your help
<?php
$data = [
"cardNumber" => "S123456789000A",
"cardholderName" => "John Doe",
];
$data = json_encode($data);
$header = $request_headers = [
"Content-Type: application/json"
];
$curl_options = [
CURLOPT_URL =>'https://gts-dm.orchitech.net/api/verifications',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_AUTOREFERER => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_FILETIME => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_USERPWD => "testdm:testdm"
];
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
var_dump($result);
The request header was not sent causing http error code 415 UnsupportedMediaTypeHttpException Hence need to add request header, working fine
I recommend you to use Postman. Just install it and try to make request with it. You'll see the result of your request and than can simply get the request code out.
You can see 'Code' on your top-right corner below 'save', press it and select your language. For your purposes it is PHP->cURL. And the result will look like this:
More about Postman here
I am trying to convert this VB script to PHP curl
xmlServerHttp.open "POST","url",False xmlServerHttp.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
xmlServerHttp.send "xmlmessage=" & Server.URLEncode(xmlDocument)
‘ xmlDocument = the Xml Document contain the actual request
xmlServerStatus = xmlServerHttp.status
if xmlServerStatus = "200" then
xmlServerResponse = xmlServerHttp.responseText
Else
Response.Appendtolog ".xmlServer status is " & xmlServerStatus
end if
This is what I have so far however it is failing
$curl = curl_init(url);
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
CURLOPT_POSTFIELDS => $xmldoc,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
);
// Setting curl options
curl_setopt_array( $curl, $options );
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
// Getting results
echo curl_exec($curl);
The API i am calling return that the xmlmessage variable is not a valid xml document.
try to change $xmlDoc to $xmlDoc->asXML()
like this
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
CURLOPT_POSTFIELDS => array('xmlmessage='=> $xmlDoc),
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
);
I'm trying to authenticate using OAuth in OpenX (site does not render well in chrome. Use iexplore or safari.)
This is my piece of code
# Login
$url = "https://sso.openx.com/api/index/token";
$post = http_build_query( array( 'Access Token URL' => 'https://sso.openx.com/api/index/token',
'Authorize URL' => 'https://sso.openx.com/login/login',
'callbackUrl' => 'oob',
'Consumer Key' => $key,
'Consumer Secret' => $secret,
'OAuth Realm' => $realm,
'Request Token URL' => 'https://sso.openx.com/api/index/initiate',
'Signature Method' => 'HMAC-SHA1 ',
'Version' => '1.0a ') );
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($resource, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$json_response = curl_exec($curl);
var_dump($json_response);
curl_close($curl);
$authObj = json_decode($json_response);
And, according to the linked documentation, I should be expecting an oauth_token and oauth_verifier:
1.Set the callbackUrl to oob (out-of-band), which tells the OAuth server that you are not redirecting a user. The OAuth Server returns the request token.
but instead I'm getting:
HTTP/1.1 400 Bad Request - Invalid Request: Missing parameters
Am I doing something obviously wrong here that I am missing? Am I misunderstanding something in the linked documentation?
Any sort of help is welcome, either aimed at the problem itself or to the way it's been presented; answers, hints, ideas, corrections, etc.
Thank you.
I am using openx too, here is my code. Hope it can help someone
$para = array (
'Access Token URL' => 'https://sso.openx.com/api/index/token',
'Authorize URL' => 'https://sso.openx.com/login/process',
'callbackUrl' => 'oob',
'Consumer Key' => $email,
'Consumer Secret' => $consumer_secret,
'OAuth Realm' => $sso_realm,
'Request Token URL' => 'https://sso.openx.com/api/index/initiate',
'Signature Method' => 'HMAC-SHA1',
'Version' => '1.0a'
);
$opt = array (
CURLOPT_URL => "https://sso.openx.com/login/process",
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_COOKIEJAR => $cookieFile,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $para,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => "{$authentication}",
CURLOPT_FOLLOWLOCATION => true
);
$c = curl_init();
curl_setopt_array($c, $opt);
$content = curl_exec($c);
$info = curl_getinfo($c);
$error = curl_error($c);
You need the "consumer_secret" and "sso_realm" from the email openx people sent to you.
Try passing the parameters like this
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
where $data will have $data='username='.$username.'&password='.$password.'';
Where does "$resource" come from?? Replace:
curl_setopt($resource, CURLOPT_POSTFIELDS, $post);
with
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
for a start.
I receive a POST request at my PHP script and would like to forward this POST call to another script using POST too. How can I do this?
I can use cURL if it's required for this action.
Perhaps:
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
From curl_setopt:
This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value.
Do this,
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($_POST));
Here's a fully functional cURL request that re-routes $_POST where you want (based on ZZ coder's reply)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://urlOfFileWherePostIsSubmitted.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// ZZ coder's part
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
$response = curl_exec($ch);
curl_close($ch);
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If need any HTTP authentication
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This can be $arrPostData = $_POST;
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your POST data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // ONLY use this when requesting JSON data
$arrResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // ONLY use this when request json data
),
// If HTTP authentication is required , use the below lines
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));