Post data using CURL in php
To POST a form remotely with CURL, we will use the simple form
- User will submit the form, as usual.
- In the form processing PHP, I use cURL to execute a POST transmission to a PHP script on the customer's server.
- The remote script would do a MySQL INSERT query into the customer's private database.NOTE: cURL extension should be enabled in your php.ini to work any curl code.See how to Enable cURL in php
Posting a Form with cURL
This is the PHP code I used to remotely POST this simple form. I’m sending ‘Mickey’ as the username and ‘Minnie’ as the password.
<?php // Define URL where the form resides $form_url = "http://www.youdomain.com/simple-post.php"; // This is the data to POST to the form. The KEY of the array is the name of the field. The value is the value posted. $data_to_post = array(); $data_to_post['username'] = 'Mickey'; $data_to_post['password'] = 'Minnie'; // Initialize cURL $curl = curl_init(); // Set the options curl_setopt($curl,CURLOPT_URL, $form_url); // This sets the number of fields to post curl_setopt($curl,CURLOPT_POST, sizeof($data_to_post)); // This is the fields to post in the form of an array. curl_setopt($curl,CURLOPT_POSTFIELDS, $data_to_post); //execute the post $result = curl_exec($curl); //close the connection curl_close($curl); ?>
In the code above, the data to post was passed as an array to the method curl_setopt(). We also passed the option CURLOPT_POSTFIELDS as a parameter.