How to Execute a HTTP POST Using PHP CURL


How do you pass $_POST values to a target url using cURL?

Asked on October 21, 2018 in PHP.
Add Comment
2 Answer(s)
Best answer
//set target url
$url = '';

//set POST variables
$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

Answered on October 21, 2018.
Add Comment


$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
# Print response.
echo "<pre>$result</pre>";
Answered on March 3, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.