Last Updated: February 25, 2016
·
20.49K
· neeph

Send a file via POST with cURL and PHP

Send file script

$target_url = 'http://127.0.0.1/accept.php';
//This needs to be the full path to the file you want to send.
$file_name_with_full_path = realpath('./sample.jpeg');
/* curl will accept an array here too.
 * Many examples I found showed a url-encoded string instead.
 * Take note that the 'key' in the array will be the key that shows up in the
 * $_FILES array of the accept script. and the at sign '@' is required before the
 * file name.
 */
$post = array('extra_info' => '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);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

Receive file script

$uploaddir = realpath('./') . '/';
$uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
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 '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
echo "\n<hr />\n";
print_r($_POST);
echo "</pre>";

Source: Send a file via POST with cURL and PHP