I have a problem with uploading files with cURL to remote server. The remote server only accepts the file only if the POST variables coming in order. In my case: sid, cmd, uploadfile I tested it with a simple HTML upload form in this order, everything ok. But if I replace the order of input fields, like: cmd, sid, uploadfile it rejects my upload.
So here is my cURL code, it doesn't send the variables in the order I set in array. How do I force cURL to POST in the same order as I set the variables.
$file = "/var/www/html/dl/big.mp4";
$target_url = 'http://upload.site/uploadpage';
$file_name_with_full_path = realpath($file);
$post = array('sid' => 'H1nbWKcdYP7eS7DzJk0Z6BjGaC842vPO', 'cmd' => 'uploadVideoFiles', 'uploadfile'=>'@'.$file_name_with_full_path);
$ch = curl_init();
$browser = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0';
curl_setopt($ch, CURLOPT_USERAGENT, $browser);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding: gzip, deflate',
'Accept-Language: en-US,en;q=0.5',
'Cache-Control: max-age=0',
'Connection: keep-alive',
'Host: upload.sitehost',
)
);
$result=curl_exec($ch);
curl_close ($ch);
echo $result;
PHP documentation says this about CURLOPT_POSTFIELDS
:
This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value.
So try using http_build_query()
instead:
<?php
$post = array('sid' => 'H1nbWKcdYP7eS7DzJk0Z6BjGaC842vPO', 'cmd' => 'uploadVideoFiles', 'uploadfile'=>'@'.$file_name_with_full_path);
$post = http_build_query($post);
...
But, setting CURLOPT_SAFE_UPLOAD
is not a great idea. Instead you should be using curl_file_create()
, so your final code could look like this:
<?php
$file = "/var/www/html/dl/big.mp4";
$target_url = 'http://upload.site/uploadpage';
$file_name_with_full_path = realpath($file);
$post = [
'sid' => 'H1nbWKcdYP7eS7DzJk0Z6BjGaC842vPO',
'cmd' => 'uploadVideoFiles',
'uploadfile'=>curl_file_create($file_name_with_full_path)
];
$post = http_build_query($post);
$ch = curl_init($target_url);
curl_setopt_array($ch, [
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0',
CURLOPT_POSTFIELDS => $post,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
]);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
I solved the problem, it was my fault, the cmd was not
'cmd' => 'uploadVideoFiles'
it was:
'cmd' => 'uploadVideoFile'