To upload a file to a server using PHP and cURL you can use the following script. If you need to make a simple POST request, without sending any file, check out my article: “POST request with cURL”.
<?php
function postRequest($url, $curl_data) {
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.53 Safari/525.19",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 9,
CURLOPT_TIMEOUT => 29,
CURLOPT_MAXREDIRS => 3,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $curl_data,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => 1,
CURLOPT_COOKIE => "",
CURLOPT_PROXY => null
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch) ;
$header = curl_getinfo($ch);
curl_close($ch);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
$file_name_with_full_path = realpath("file_to_upload");
if (function_exists('curl_file_create')) // php 5.5+
$cFile = curl_file_create($file_name_with_full_path);
else
$cFile = '@' . realpath($file_name_with_full_path);
$postData = array("file" => $cFile);
echo print_r(postRequest("http://targeturl.com", $postData), true);
?>