Before going to know how to post form data and file with cURL, i will tell you, what is cURL in PHP and how will you use cURL in PHP script.
cURL is a library and command line tool which is used to get and send file using URL syntax and become powerful system.
cURL was released in 1997 and it was known as "See URL" when it was released.
cURL supports various protocols including HTTP, HTTPS, FTP, FTPS, TFTP, SCP, SFTP, LDAP, DAP, DICT, TELNET, FILE, IMAP, POP3, SMTP and RTSP.
Mostly we use cURL for accessing third-party API system like : sending sms via API using cURL.
Now a days developers call it "curl in PHP".
Steps to use cURL- First i initialize curl session by using
curl_init
method. - Second i set different option for curl session by using
curl_setopt
method and some are optional. - Third i execute curl session to get and send data over server by using
curl_exec
. - Fourth i close the curl session by using
curl_close
which i have created. - Now you can display response data.
Here you will fine basic cURL example.
- function getContent($url, $postdata = false)
- {
- // check if cURL installed or not in your system?
- if (!function_exists('curl_init')){
- return 'Sorry cURL is not installed!';
- }
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
- if ($postdata)
- {
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
- }
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 ;Windows NT 6.1; WOW64; AppleWebKit/537.36 ;KHTML, like Gecko; Chrome/39.0.2171.95 Safari/537.36");
- $contents = curl_exec($ch);
- $headers = curl_getinfo($ch);
- curl_close($ch);
- return array($contents, $headers);
- }
You can send post data to define option CURLOPT_POST
and data will be passed with CURLOPT_POSTFIELDS
option.
Now i will tell you some cURL command to posting form data.
Use curl -X POST
and add -F
for every parameters which you want to add to the POST.
- curl -X POST -F 'field1=value1' -F 'field2=value2' http://your-domain.com/page.php
Now on server you can receive these data by using $_POST
and if you want to see data to make sure then you can print $_POST
variable by using print_r
method.
- Array(
- 'field1' => 'value1',
- 'field2' => 'value2'
- )
You can send header or specific data type with cURL then use -H
to add header.
- curl -X POST -H 'Content-Type: application/json' -d '{"field1":"davidwalsh","field2":"something"}' http://your-domain.com/page.php
-d
is using to send raw data.
You can send files with cURL but make sure while sending files with cURL you will have to add @
before the file path.
- curl -X POST -F 'image=@/image-path/mypicture.jpg' http://your-domain.com/upload-image
You can access files on server by using $_FILES
variable.