Skip to content

Instantly share code, notes, and snippets.

@otkrsk
Created November 25, 2016 04:54
Show Gist options
  • Save otkrsk/357785077bfb33eb8964cfa512aa4d1e to your computer and use it in GitHub Desktop.
Save otkrsk/357785077bfb33eb8964cfa512aa4d1e to your computer and use it in GitHub Desktop.
Send $_POST Request Using PHP cURL
//extract data from the post
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname' => urlencode($_POST['last_name']),
'fname' => urlencode($_POST['first_name']),
'title' => urlencode($_POST['title']),
'company' => urlencode($_POST['institution']),
'age' => urlencode($_POST['age']),
'email' => urlencode($_POST['email']),
'phone' => urlencode($_POST['phone'])
);
//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);
@matefs
Copy link

matefs commented Apr 12, 2019

Can you explain me what the command: "foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }" do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment