Tutorials

How to pass $_POST variables via PHP CURL

If you wish to pass PHP POST array variables without submitting a form, using the PHP Curl library to another URL, you first need to have a an Array which holds all the values for the POST array

$post['lname'] = 'Last name';
$post['fname'] = 'First Name'
$post['mail'] = 'example@mail.com';

Once we have the array set, we create the variables for the destination URL and POST fields

$url = 'http://example.com/get-the-post-data.php';
$fields = array ('lname' =>urlencode($post['lname'],
'fname' = urlencode($post['fname']),
'mail' = urlencode($post['mail']));

Now we need a variable with all the post fields in the format which can be sent through curl

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

Now we start the Curl Connection and send the post data through the curl request

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
//check the result
var_dump($result);

Copyright © 2018 WPOven