Send server stored PDF file to another server via Curl PHP form data
P粉521748211
2023-08-31 12:44:11
<p>I'm trying to send a PHP file stored on my server to another server via Curl PHP Form Data method. </p>
<p>Normally this is done by submitting the form and uploading a file and sending the same file as form data to the Curl PHP endpoint, but in this case I already have the file on my server and I Stuck on the part of how to get the file and create its form data array and send the API Url as post method. </p>
<p>Below is some kind of program I'm trying. One of them is to create a tmp file and store data in it and send that data from tmp location to curl form data. </p>
<p>$source = file_get_contents("https://url/employee_manual3.pdf");</p>
<pre class="brush:php;toolbar:false;">$tempFile = tempnam(sys_get_temp_dir(), 'File_');
rename($tempFile, $tempFile .= '.pdf');
file_put_contents($tempFile, $source);
// var_dump($tempFile);
//exit;
// $post = array(
// "uploadedFile" => "@" . $tempFile, //"@".$tempFile.";type=application/pdf",
// );
// var_dump(file_get_contents($tempFile));
// var_dump(new CURLFILE($tempFile));
//exit;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://API_URL',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('file' => new CURLFILE($tempFile)),
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer API TOKEN HAI MERA',
'Content-Type: multipart/form-data',
'Cookie: MAIN NAHI BATAUNGA'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;</pre>
<pre class="brush:php;toolbar:false;"></pre></p>
Hi, you can check out the answer below to see how I managed to achieve this.