Archive for category cURL

Posting or Uploading Files using cURL with PHP

cURL - groks those URLs

groks URLs

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.

 Read the rest of this entry »

Tags: , , , , , ,

PHP – Downloading a File from Secure website (https) using CURL

Recently in one of my project I was suppose to download file from a secure website. Actually I have to set the scheduler job for downloading nightly builds/full files from the server and the files are placed on secure website.

Initially I tried that with file_get_contents function but it was just downloading 0KB file. Then it strike me that oh..! I can't use file_get_contents as it can't understand the HTTPS protocol here. So what could help me nothing else then our best friend CURL. file_get_contents and fopen kind of other functions works fine with any http web locations.

Here is the simple CURL file transfer function snippet which will copy file from any secure http location. Read the rest of this entry »

Tags: , , ,

Paying the bills.!