The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead

9.7k Views Asked by At

I am beginner to php and i was exercising by HP's IDOL OnDemand api to extract texts from any image file.

I had to set a curl connection and execute api request but when i try to post file by using @ method, in php 5.5 its deprecated and recommends me to use CURLFile.

I also digged php manuals and came up with something like this https://wiki.php.net/rfc/curl-file-upload

Code is as below:

$url = 'https://api.idolondemand.com/1/api/sync/ocrdocument/v1';

$output_dir = 'uploads/';
if(isset($_FILES["file"])){

$filename = md5(date('Y-m-d H:i:s:u')).$_FILES["file"]["name"];

move_uploaded_file($_FILES["file"]["tmp_name"],$output_dir.$filename);

$filePath = realpath($output_dir.$filename);
$post = array(
    'apikey' => 'apikey-goes-here',
    'mode' => 'document_photo',
    'file' => '@'.$filePath
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

unlink($filePath);

If any rewrite code and show me how to use Curlfile i would be appreciate.

Thanks,

2

There are 2 best solutions below

0
On BEST ANSWER

I believe it's as simple as changing your '@'.$filePath to use CurlFile instead.

$post = array('apikey' => 'key', 'mode' => 'document_photo', 'file' => new CurlFile($filePath));

The above worked for me.

Note: I work for HP.

0
On

Due to time pressure, I did a quick workaround when I integrated a third party API. You can find the code below.

$url: Domain and page to post to; for example http://www.snyggamallar.se/en/ $params: array[key] = value format, just like you have in $post.

WARNING: Any value that begins with an @ will be treated as a file, which of course is a limitation. It does not cause any issues in my case, but please take it into consideration in your code.

static function httpPost($url, $params){
    foreach($params as $k=>$p){
        if (substr($p, 0, 1) == "@") { // Ugly
            $ps[$k] = getCurlFile($p);
        } else {
            $ps[$k] = utf8_decode($p);
        }
    }

    $ch = curl_init($url);
    curl_setopt ($ch, CURLOPT_POST, true);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $ps);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

    $res = curl_exec($ch);
    return $res;
}

static function getCurlFile($filename)
{
    if (class_exists('CURLFile')) {
        return new CURLFile(substr($filename, 1));
    }
    return $filename;
}