How can you ensure that the MIME type of the file being uploaded via cURL in PHP is correct?

When uploading a file via cURL in PHP, you can ensure that the MIME type is correct by setting the appropriate Content-Type header in the cURL request. This ensures that the server receiving the file knows how to interpret the data being sent. You can use the finfo_file function to determine the MIME type of the file before sending it.

// Get the MIME type of the file
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file_path);
finfo_close($finfo);

// Set the Content-Type header in the cURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'file' => new CURLFile($file_path, $mime),
]);
curl_exec($ch);
curl_close($ch);