这是最基本的方法:
$url = "http://other-site/image.png";
$dir = "/my/local/dir/";
$rfile = fopen($url, "r");
$lfile = fopen($dir . basename($url), "w");
while(!feof($url)) fwrite($lfile, fread($rfile, 1), 1);
fclose($rfile);
fclose($lfile);
但是,如果您正在做很多这样的事情(或者您的主机阻止了对远程系统的文件访问),请考虑使用 CURL,它更高效、速度稍快且可在更多共享主机上使用。
您还可以将用户代理伪装成桌面而不是机器人!
$url = "http://other-site/image.png";
$dir = "/my/local/dir/";
$lfile = fopen($dir . basename($url), "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);
fclose($lfile);
curl_close($ch);
对于这两个实例,您可能希望通过 GD 传递它以确保它确实是图像。