简体   繁体   中英

CURL Warning: curl_file_create() expects parameter 1 to be a valid path, string given

I don't know why this is not working. I am trying to download a image from a URL then sent it via CURL. POST request the path with var_dump is working, but with CURL it doesn't work

The error is

Warning: curl_file_create() expects parameter 1 to be a valid path, string given

// define('TMP', __DIR__ . DIRECTORY_SEPARATOR . 'tmp');
/**
 * @param $url
 * @return string
 */
function dlImage($url) {
    $save_dir = TMP . DIRECTORY_SEPARATOR;
    $filename = basename($url);
    $save = $save_dir.$filename;
    file_put_contents($save,file_get_contents($url));
    return $save;
}
    
function upload( $body, $title, $type, $type_real, $subCat, $poster = null, $imdbUrl = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'xxxx');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    $data = [
        'key' => 'xxxx',
        'type' => $type,
        'subtype' => $subCat,
        'type_real' => $type_real,
        'title' => $title,
        'posterUpload' =>  curl_file_create(realpath(dlImage($poster)),'image/jpeg'),
        'imdbUrl' => $imdbUrl,
    ];
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    curl_close($ch);
    var_dump($result);
}
// path is working fine 
dlimage output (var_dump) : string(113) 

"C:\laragon\www\api\tmp\MV5BNDliY2E1MjUtNzZkOS00MzJlLTgyOGEtZDg4MTI1NzZkMTBhXkEyXkFqcGdeQXVyNjMwMzc3MjE@.jpg" 

add more error checking, replace

        file_put_contents($save,file_get_contents($url));

with

$content=file_get_contents($url);
if(!is_string($content)){
    throw new \RuntimeException("failed to fetch url {$url}");
}
if(($len=strlen($content))!==($written=file_put_contents($save,$content))){
    throw new \RuntimeException("could only write {$written}/{$len} bytes to file {$save}");
}

then you should probably get an errorlog explaining where things went wrong, and my best guess is that things went wrong with file_get_contents() and/or file_put_contents().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM