PHP Send local cURL file
I am trying to send a local file by a client. I found some examples to do this with files from a form. In my case, I don't have a form, but a local file.
$fileName = $_SERVER["DOCUMENT_ROOT"]."/www/images/test.pdf";
if(!file_exists($fileName)) {
$out['status'] = 'error';
$out['message'] = 'File not found.';
exit(json_encode($out));
}
$data = array('name' => 'Foo', 'file' => '@'.$fileName);
$cURL = curl_init("http://myapi/upload-images");
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_POST, 1);
curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($cURL);
$error = curl_error($cURL);
curl_close($cURL);
die($response);
At the same time, I don't have erros, but on the server the $ _POST and $ _SERVER arrays are empty.
I tried differently, this time creating a Curl file before submitting:
// Mime type of file
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $fileName);
$cFile = new CURLFile($fileName, $finfo, "file");
//var_dump($cFile);
//CURLFile Object
//(
// [name] => C:/.../test.pdf
// [mime] => application/pdf
// [postname] => file
// )
$cURL = curl_init("http://myapi/upload-images");
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS,
array(
'file' => $cFile
));
$response = curl_exec($cURL);
curl_close($cURL);
die($response);
The same answer. $ _FILES is empty.
+3
source to share
1 answer
Finally, I found the cause of the problem. The file data array must have filedata and file names.
We can pass '@' before the full path filename, but this is deprecated.
$data = array( "filedata" => '@'.$fileName, "filename" => basename($fileName));
In this case, I added a Curl object:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $fileName);
$cFile = new CURLFile($fileName, $finfo, basename($fileName));
$data = array( "filedata" => $cFile, "filename" => $cFile->postname);
Complete code:
$fileName = $_SERVER["DOCUMENT_ROOT"]."/www/images/test.pdf";
$fileSize = filesize($fileName);
if(!file_exists($fileName)) {
$out['status'] = 'error';
$out['message'] = 'File not found.';
exit(json_encode($out));
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $fileName);
$cFile = new CURLFile($fileName, $finfo, basename($fileName));
$data = array( "filedata" => $cFile, "filename" => $cFile->postname);
$cURL = curl_init("http://myapi/upload-images")
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
// This is not mandatory, but is a good practice.
curl_setopt($cURL, CURLOPT_HTTPHEADER,
array(
'Content-Type: multipart/form-data'
)
);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);
curl_setopt($cURL, CURLOPT_INFILESIZE, $fileSize);
$response = curl_exec($cURL);
curl_close($cURL);
die($response);
+3
source to share