cURL is very important tool for PHP programmers, we tends to do so many thing with using this tool. Posting data, imitating a form post and lot more, it's usage is countless. Some time back I came across situation where we have to post files to a 3rd party faxing service. I knew there are many possibilities but I didn't wanted to get into sockets and file stream to get this done, just wanted to post FILE in addition to rest of the post data.
// URL on which we have to post data $url = "http://localhost/tutorials/post_action.php"; // Any other field you might want to catch $post_data['name'] = "khan"; // File you want to upload/post $post_data['file'] = "@c:/logs.log"; // Initialize cURL $ch = curl_init(); // Set URL on which you want to post the Form and/or data curl_setopt($ch, CURLOPT_URL, $url); // Data+Files to be posted curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // Pass TRUE or 1 if you want to wait for and catch the response against the request made curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // For Debug mode; shows up any error encountered during the operation curl_setopt($ch, CURLOPT_VERBOSE, 1); // Execute the request $response = curl_exec($ch); // Just for debug: to see response echo $response;
Above Code is the bare minimum required to post/upload file using CURL. As used in above example, it's not mandatory to use array index as "file". You can use anything required depending upon the requirement.
Posting multiple files is also easy, with the same code you can add multiple file upload using following lines:
$post_data['alian_error_log'] = "@c:/alian_app_error.log"; $post_data['myapp_error_log'] = "@c:/myapp_error.log";
Here @ is the key character, prefixing local file path with @ does all the trick.
curl is a command line tool for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and a busload of other useful tricks.