Send a file via POST with cURL and PHP

cURL is a great library. It can do just about anything that a normal web browser can do including send a file via a post request.

This makes it really easy to transmit files between computers. In my case, I was looking for an easy way to send images snapped by various webcam systems to a central server with php managing the images.

Here is a simple script to send a file with php/cURL via POST:

 '123456','file_contents'=>'@'.$file_name_with_full_path);

        $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$target_url);
	curl_setopt($ch, CURLOPT_POST,1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$result=curl_exec ($ch);
	curl_close ($ch);
	echo $result;
?>

And here is the corresponding script to accept the file.

';
	if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
	    echo "File is valid, and was successfully uploaded.\n";
	} else {
	    echo "Possible file upload attack!\n";
	}
	echo 'Here is some more debugging info:';
	print_r($_FILES);
	echo "\n
\n"; print_r($_POST); print "\n"; ?>

And that's it.
Navigate to the 'send' script and it will transmit the file sample.jpeg to the accept script.

Note that you can include other arguments in the post along with the file. This allows you to authenticate the upload. I'm using pre-shared strings to 'validate' that upload came from my send script.

This works with the command line version of php too.

 

UPDATE Oct. 2014 – 

If you're using PHP 5.5 or better, check out the recently added 'CurlFile' class which makes the whole process a lot easier.

 

References:
http://us3.php.net/manual/en/function.move-uploaded-file.php
http://us3.php.net/manual/en/features.file-upload.post-method.php
http://curl.haxx.se/libcurl/php/examples/multipartpost.html
http://forums.devshed.com/php-development-5/php-curl-send-a-file-533233.html