PHP cURL Part 4(Form Submission)
08/04/2019 . 1 minute, 51 seconds to read . Posted by Admin#php #curl #phpcurl
So far, we've learned the following features of PHP cURL in this series of articles.
- PHP cURL Basics (1st part)
- Getting Contents of any URL (2nd part)
- Downloading File from URL (3rd part)
- Checking URL existence
In this article, we'll learn how to submit any form using PHP cURL. There are many cases where we need to submit any form automatically without user interaction. For example, login pages are forms and we can submit those forms and login into most of the sites automatically using PHP cURL.
Following code snippet is a very basic example of form submission using PHP cURL.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://httpbin.org/post");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$data = array(
'first_name' => 'John',
'last_name' => 'Smith',
'user_name' => 'john',
'email' => 'john.smith@gmail.com',
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
curl_close($curl);
echo '<pre>',$result;
Explanation:
Most of the cURL options have been discussed in our previous parts of the article. Here is a short description
- CURLOPT_URL: used set target URL.
- CURLOPT_RETURNTRANSFER: used to direct cURL to not display response(default) but return after execution.
- CURLOPT_SSL_VERIFYPEER: used to enable or disable SSL.
We've used two new options in this article.
CURLOPT_POST
To submit the form we normally use post method. CURLOPT_POST is used to tell PHP cURL that it's a post request or not.
CURLOPT_POSTFIELDS
This option is used to set the form data in the request.
Response:
HTTP Bin is used to test HTTP requests. It returns the request data as a response, you can see we got all of our data in the response which means PHP cURL has submitted form successfully.
{
"args": {},
"data": "",
"files": {},
"form": {
"email": "john.smith@gmail.com",
"first_name": "John",
"last_name": "Smith",
"user_name": "john"
},
"headers": {
"Accept": "*/*",
"Content-Length": "468",
"Content-Type": "multipart/form-data; boundary=------------------------cd2b860537d5efbd",
"Host": "httpbin.org"
},
"json": null,
"origin": "103.255.6.78, 103.255.6.78",
"url": "https://httpbin.org/post"
}
That's all for this part of the article. In the next part, we'll learn Authentication using PHP cURL.
Thanks for reading.