Friday, July 6, 2018

[PHP] 簡單的抓圖程式 (使用 file_get_contents)

<?php
$url = 'http://aaa.bbb.ccc/img/a.jpg';
$img = download_img($url);
echo $html_img = '<img src="'.$img.'">';

function download_img($url) {
    $dir = 'my_img/';
    $file_data = file_get_contents($url);
    if ($file_data) {
        $file_ext = '.jpg';
        $basename = date('YmdHis') . "_" . rand(100, 999) . $file_ext;
        $filename = $dir . $basename;
        file_put_contents($filename, $file_data);
        return $dir . $basename;
    } else {
        return false;
    } 
}

No comments:

Post a Comment