How to send form variables to multiple URLs in php (cURL?) - php

I seem to have run into a problem with trying to submit form variables to multiple urls.
The code i have below takes variables from a form and stores them in php, then I am trying to send those variables to certain urls (the variables do pass through, I've tested that). I heard cUrl is the way to do it, but I don't know if its working cause im stumped on how to to retrieve the response code.
<?php
$name = $_POST['firstname'];
$email = $_POST['email'];
$src = $_POST['srcUrl'];
$ip= $_SERVER['SERVER_ADDR'];
$suDate = date('Y-m-d H:i:s');
$data = array(
"fn" => $name,
"src" => $src,
"em" => $email,
"ip" => $ip,
"signupDate" => $suDate
);
$data2 = array(
"firstname" => $name,
"email" => $email,
);
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
post_to_url("http://exampleURL.com/page.php", $data);
post_to_url("http://exampleURL2.com/cgi-bin/add.cgi", $data2);
print_r($result);
?>
any help is greatly appreciated. thanks

In the code example you've provided above, $result contains the response you're looking for. To view the full details of the variable, use this:
print_r($result);
print_r is useful when you're not sure what data type a variable is or what data it might contain. print_r gives you all available information on the variable.
Edit: Also change curl_setopt($post, CURLOPT_POST, count($data)); to curl_setopt($post, CURLOPT_POST, 1); CURLOPT_POST is a true/false option (http://php.net/manual/en/function.curl-setopt.php).

Inside your function where you have $result = curl_exec($post); the $result data is the response. So you need to add return $return; and call the function with $response = post_to_url(...); and echo the response.

Related

How to make and pass an object with multiple keys into a php curl http post

As a premise, I have written a bunch of endpoints for one of my company's portals using nodejs. Now I have to make the same functionality in another one of our portals but this portal was built in php... And I am VERY new to php.
What I have works, but it just seems sloppy and I end up having to do some string manipulation in the endpoint to get out what I need. Also, I'm pretty sure I'm not using curl the way I'm supposed to. Any help would be appreciated.
Here is what I have
$params = array('userID' => $userID, 'UnitID' => $unitid);
foreach ($params as $key => $value) {
$params .= $key . "=" . $value . "&";
}
$url = 'https://10.4.2.31:4000/api/TestCurl/' . $params;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_POST,2);
curl_setopt($ch,CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
print $result;
curl_close($ch);
And an example of the result I'm getting in node is
{params: 'ArrayuserID=12345678&UnitID=ABC1234&'}
My test endpoint in looks like this
app.post('/api/TestCurl/:params', UserCtrl.TestCurl);
You can use http_build_query() to convert an array into a format for use with curl.
For a POST request:
$params = array('userID' => $userID, 'UnitID' => $unitid);
$fields_string = http_build_query($params);
// ...
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
The reason for the output you give is that you are defining $params as an array, but then concatenating it as a string inside the foreach loop. Your approach would work if you used a different variable name inside the loop.

Posting to XML with cURL, Noob here learning

Hi I'm trying to program with cURL.
But haven't started also it return me wit server internal error.
Is there any wrong with the given code in the cURL?
<?php';
$now = new DateTime();
$url = "smsx.ia.com.my";
$parameters = array(
'UserID' => 'something#gmail..com',
'Version' => '1.0',
'Action' => 'ProductCreate',
'Timestamp' => $now->format(DateTime::ISO8601),
);
// Sort parameters by name
ksort($parameters);
$params = array();
foreach ($parameters as $name => $value) {
$params[] = rawurlencode($name) . '=' . rawurlencode($value);
}
$strToSign = implode('&', $params);
// Compute signature and add it to the parameters
$parameters['Signature'] =
rawurlencode(hash_hmac('sha256', $strToSign, $api_key, false));
// Build Query String
$queryString = http_build_query($parameters, '', '&', PHP_QUERY_RFC3986);
// Open Curl connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url."?".$queryString);
// Save response to the variable $data
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlPayload);
$data = curl_exec($ch);
// Close Curl connection
curl_close($ch);
if (isset($_POST['Submit'])) {
}
?>
<form action="" method="post">
<input type="submit">
</form>
So I'm trying to post information to the URL, but i just load the site and it gives me system internal error.
Can't proceed with it.
Any idea why I'm facing this issue?
First of all, if you are posting XML data then you have to specify the server that you are sending XML in post data. I can't see this in your code.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml; charset=utf-8'));
Secondly, make sure your are preparing your $queryString thing correctly. Otherwise it may raise internal server error too.
Finally, just curious, are you sure about '; after <?php at the first line of your code?

cURL not actually sending POST data

Overview
I have a script, we'll call it one.php, that creates a database and tables. It also contains an array of data to be posted to another script, two.php, which will sort through the data and insert it into our newly created database.
Your help is much, much appreciated.
The Problem
two.php has a check for the $_POST[] array at the very top of the script:
if (empty($_POST))
{
$response = array('status' => 'fail', 'message' => 'empty post array');
echo json_encode($response);
exit;
}
Normally, this would not be triggered unless the post array is, well, empty(). However, when sending the data from one.php to two.php via cURL, I'm receiving the above encoded array as my response, and my data does not progress further down two.php.
I'll lay out the relevant code from the files below for your viewing pleasure:
one.php
$one_array = array('name' => 'John', 'fav_color' => 'red');
$one_url = 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/two.php';
$response = post_to_url($one_url, $one_array, 'application/json');
echo $response; die;
This is currently giving me the below:
{"status":"fail","message":"empty post array"}
The post_to_url() function, for reference
function post_to_url($url, $array, $content_type)
{
$fields = '';
foreach($array as $key => $value)
{
$fields .= $key . '=' . $value . '&';
}
$fields = rtrim($fields, '&');
$ch = curl_init();
$httpheader = array(
'Content-Type: ' . $content_type,
'Accept: ' . $content_type
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
two.php
header("Content-type: application/json");
$response = array(); //this is used to build the responses, like below
if (empty($_POST))
{
$response['status'] = 'fail';
$response['message'] = 'empty post array';
echo json_encode($response);
exit;
}
elseif (!empty($_POST))
{
//do super neat stuff
}
Because you're setting the request body content type as "application/json", PHP will not populate $_POST in "two.php". Because you're sending url encoded data, the best thing to do is only send the Accept: header:
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
That said, "two.php" doesn't actually use the Accept: header and always outputs JSON; in that case, you can make do with not setting CURLOPT_HTTPHEADER at all.
Update
Creating url encoded data from an array can be simpler (and safer) too:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
I have some issue like that, but in my case I added
Content-Type: {APPLICATION/TYPE}
Content-Length: {DATA LENGTH}
and problem was solved.

php retrieve curl_setopt POSTFIELDS string

Is there any way to retrieve the curl_setopt POSTFIELDS string which I had posted to the site after the curl_multi_exec($mh, $running) command?
Thanks.
You have to keep that data together with the individual resources:
$handles = array();
foreach ($urls as $url) {
$ch = curl_init($url);
$data = 'whatever';
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$handles[$url] = array(
'ch' => $ch,
'data' => $data,
);
}
This keeps the cURL handles and data together in a single structure that you can later use to inspect.
foreach($handles as $url => $data) {
// $url is the page you requested for this particular handle
// $data['data'] contains the data that goes with it
$body = curl_multi_getcontent($data['ch']);
curl_multi_remove_handle($mh, $data['ch']);
curl_close($data['ch']);
}

CURL PHP POST interferes with JSON

I currently have an API script that returns JSON. It has worked up until I tried to add in a curl php POST script before it. The curl script is working on it's own, and it is also working in the API script. However the JSON code is not being returned.
Is there something fundamentally wrong with this approach below?
Thanks in advance.
EDIT: The curl script works 100% on its own.
Said script is also working inside the below, it's just that the JSON does not return.
$name = "foo";
$age = "bar";
//set POST variables
$url = 'https://www.example.com';
$fields = array(
'name' => urlencode($name),
'age' => urlencode($age)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return json_encode(
array(
"status" => 1,
"message" => "Success!",
"request" => 10
)
);
You need to do the following use echo and also use CURLOPT_RETURNTRANSFER if not the output would be transferred directly to the page instead of $result
$name = "foo";
$age = "bar";
$url = 'http://.../a.php';
$fields = array('name' => urlencode($name),'age' => urlencode($age));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
header('Content-type: application/json');
echo json_encode(array("status" => 1,"message" => "Success!","request" => 10));

Categories