How can I forward $_POST with PHP and cURL? - php

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&para2=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
));

Related

How to prevent wp_remote_post to add backslashes

To publish a plugin I must change my code to use the Wordpress HTTP Api.
Therefore, I have translate my code.
Before.
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
After
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$result = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json'),
'body' => wp_json_encode($data_string),
'method' => 'POST',
'timeout' => 60, // added
'redirection' => 5, // added
'blocking' => true, // added
'httpversion' => '1.0',
'sslverify' => false,
));
But with the function wp_remote_post I have this problem.
When JSON data is sended to remote host, the data has the backslashes inside.
Example:
{\"Param1\":\"ValueParam1\","Param2\":\"ValueParam2\"}
What is wrong?
Have I wrong something in translate the origin code?
I need some help to send JSON data without these escaping characters.
Thanks.
Pass JSON_HEX_QUOT as a second parameter to wp_json_encode to escape the double quotes without a slash. See: https://developer.wordpress.org/reference/functions/wp_json_encode/ and https://www.php.net/manual/en/json.constants.php for more details.

JSON Error on posting Data using PHP

Following is the coding I have done. But after posting the data, I am getting error as:
'message' => string ''from' and 'to' date must be given' (length=34).
Following is my code:
$auth_token=$_REQUEST['auth_token'];
$ch = curl_init('https://api.datonis.io/api/v3/datonis_query/thing_aggregated_data');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'X-Auth-Token:'.$auth_token,
'thing_key:6f2159f998',
'idle_time_required:true',
'from:2016/02/02 17:05:00',
'to:2016/08/29 17:10:00',
'time_zone:Asia/Calcutta',
'Content-Type:application/json',
),
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
//var_dump($response);
$responseData = json_decode($response, TRUE);
// Print the date from the response
var_dump($responseData);
Actually I also want to get the data but the details are contained in the post request data.
use "CURLOPT_POSTFIELDS":
$data = array("from" => "2016/02/02 17:05:00", "to" => "2016/08/29 17:10:00");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')

Error on cURL request using php-cURL while sending SMS

The request entity's media type 'multipart/form-data' is not
supported for this resource.\",\"ExceptionMessage\"unsure emoticon"No
MediaTypeFormatter is available to read an object of type 'SmsQueue'
from content with media type
'multipart/form-data'.\",\"ExceptionType\"unsure
emoticon"System.Net.Http.UnsupportedMediaTypeException\",\"StackTrace\"unsure
emoticon" at
System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent
content, Type type, IEnumerable 1 formatters, IFormatterLogger
formatterLogger, CancellationToken cancellationToken)\r\n at
System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage
request, Type type, IEnumerable`1 formatters, IFormatterLogger
formatterLogger, CancellationToken cancellationToken)\"}"
// Prepare you post parameters
$postArray = array(
'APIKey' => AUTH_KEY,
'number' => $mobile,
'text' => $message,
'senderid' => SENDER_ID,
'channel' => $channel,
'DCS' => $DCS,
'flashsms' => $flashsms,
'route' => $route
);
// Init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postArray
));
// Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Get response
$curlOutput = curl_exec($ch);
// Print error if any
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
CURLOPT_POSTFIELDS => http_build_query($postArray) not working
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS => http_build_query($postRequest1));
Set Content-Type in header to application/x-www-form-urlencoded.
Use like this :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://url.com",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query(['message' => test]),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded'
),
));

POST works on Postman, but not with CURL

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

How to get an oauth_token with oAuth in PHP

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.

Categories