php實現下載圖片的方法

2021-03-11 10:01:29

php實現下載圖片的方法:1、使用「file_get_contents」實現下載圖片;2、通過使用CURL實現下載圖片;3、通過使用fopen實現下載圖片即可。

本文操作環境:windows7系統、PHP7.1版,DELL G3電腦

PHP下載遠端圖片的幾種方法總結

本文演示3個從遠端URL下載圖片,並儲存到本地檔案中的方法,包括file_get_contents,curl和fopen。

1、使用file_get_contents

function dlfile($file_url, $save_to)
{
 $content = file_get_contents($file_url);
 file_put_contents($save_to, $content);
}

2、使用CURL

function dlfile($file_url, $save_to)
{
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_POST, 0); 
 curl_setopt($ch,CURLOPT_URL,$file_url); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
 $file_content = curl_exec($ch);
 curl_close($ch);
 $downloaded_file = fopen($save_to, 'w');
 fwrite($downloaded_file, $file_content);
 fclose($downloaded_file);
}

3、使用fopen

function dlfile($file_url, $save_to)
{
 $in=  fopen($file_url, "rb");
 $out=  fopen($save_to, "wb");
 while ($chunk = fread($in,8192))
 {
 fwrite($out, $chunk, 8192);
 }
 fclose($in);
 fclose($out);
}

下載與儲存完整方法(輸出紀錄檔那行可刪除):

    private function downloadImage($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $this->saveAsImage($url, $file);
    }
    private function saveAsImage($url, $file)
    {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME);
        $path =  'public' . $dirname . '/';
        $fullpath =  'public' . $dirname . '/' . $filename;
        // 如果目錄不存在,則建立
        if(!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if(file_exists($fullpath)) {
            //$this->output->writeln("【已存在】輸出路徑" . $fullpath);
        } else {
            $resource = fopen($fullpath, 'a');
            fwrite($resource, $file);
            fclose($resource);
            //$this->output->writeln("【已儲存】輸出路徑" . $fullpath);
        }
    }

【推薦學習:《》】

以上就是php實現下載圖片的方法的詳細內容,更多請關注TW511.COM其它相關文章!