У меня есть старый скрипт, который загружает файлы PDF через API. Я получаю сообщение об ошибке:
Deprecated: curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead.
Вот соответствующий код (я думаю, это все). Ошибка указывает на строку: curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, $postFields ).
//Upload the file
function uploadPdf( $api, $lead_id, $rev, $existing_files = array() ) {
if ( ! file_exists( SERVERPATH . "quotes/quote-". $this->id .".pdf" ) )
$this->createQuotePdf();
$files_array = array( array( 'entityType'=>'files', 'name'=>"quote-". $this->id .".pdf" ) );
// if ( $this->upfile && ! file_exists( SERVERPATH . "uploads/" . $upfile ) )
// $files_array[] = array( array( 'entityType'=>'files', 'name'=> $upfile ) );
foreach ( $existing_files as $file ) {
$files_array[] = (array) $file;
}
//this request gives us the URLs to upload to
$result = $api->editLead( array( 'leadId' => $lead_id, 'rev'=>'REV_IGNORE', 'lead'=> array( 'file' => $files_array ) ) );
//Upload the Quote file
$postFields = array();
$postFields['file'] = "@" . SERVERPATH . "quotes/quote-". $this->id .".pdf";
$postFields['type'] = "application/pdf";
$curl_handle = curl_init();
$file = array_pop( $result->file );
curl_setopt( $curl_handle, CURLOPT_URL, $file->uri );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_handle, CURLOPT_POST, true );
curl_setopt( $curl_handle, CURLOPT_USERPWD, USERNAME . ":" . API_KEY );
curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, $postFields );
//execute the API Call
$return = curl_exec( $curl_handle ) ;
$this->uploadUpfile($api, $lead_id);
return $return;
}
Мои знания довольно базовые. Но я попытался заменить:
$postFields['file'] = "@" . SERVERPATH . "quotes/quote-". $this->id .".pdf";
$postFields['type'] = "application/pdf";
с
$postFields['file'] = curl_file_create(SERVERPATH . "quotes/quote-". $this->id .".pdf", 'application/pdf', SERVERPATH . "quotes/quote-". $this->id .".pdf");
Выполнение описанного выше позволило избавиться от ошибки, но основная проблема, при которой я не могу открыть загруженный файл, все еще возникает. Так что мне интересно, сделал ли я что-то не так?
Явно отвечая на вопрос «Это способ решения ошибки« Устарело: curl_setopt (): »?» - Да. Используйте что-нибудь другое. Это устарело.






Начиная с PHP 5.5 и выше, вы должны использовать CURLFile для загрузки файла, я уже опубликовал полный ответ, описывающий CURLFile и обычную загрузку файла, вы можете проверить этот ответ здесь.
Вы можете использовать CURLFile, как показано ниже, не стесняйтесь настраивать код в соответствии с вашими потребностями:
//Upload file using CURLFile
function upload($target, $postFields){
$file = $postFields['file'];
$cFile = new CURLFile($file,$postFields['type'], $file);
$data = array(
'file' => $cFile,
'type' => $postFields['type'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_HEADER , true); //we need header
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$r = curl_exec($curl);
if (curl_errno($curl)) {
$error = curl_error($curl);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfull
print_r($r);
}
}
curl_close($curl);
}
Поскольку ваш файл и тип файла находятся в массиве с именем $postFields, вы можете вызвать указанную выше функцию, как показано ниже:
upload($target, $postFields);
где $target - ссылка, по которой вы вызываете загрузку файла.
Спасибо за вашу помощь, Теджашви - я только что отредактировал код в исходном вопросе, чтобы показать полную функцию, чтобы, надеюсь, дать более полную картину. Поскольку в моей функции файл находится в массиве, мне нужно изменить здесь вашу строку: $ file = "@". СЕРВЕРПАТ. "цитаты / цитата-". $ this-> id. ". pdf"; или любая другая линия?
Правильно, вы используете php.net/manual/en/class.curlfile.php или php.net/manual/en/function.curl-file-create.php вместо обозначения
@