<?php
function saveImage($url) {
if (!preg_match('/\/([^\/]+\.[a-z]{3,4})$/i', $url, $m)) die('Invalid image URL');
$fname = strtolower($m[1]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$img = curl_exec($ch); curl_close($ch);
$fp = fopen($fname, 'w'); fwrite($fp, $img); fclose($fp);
}
saveImage('https://www.example.com/images/logo.jpg');
?>
自動從 URL 擷取檔名,二進位模式寫入。生產環境建議加入副檔名白名單、檔案大小限制、錯誤重試。