Tôi cần lưu hình ảnh từ url trực tiếp vào máy chủ của mình, tôi đã thử nhiều phương pháp nhưng tất cả dường như không hoạt động đúng cách. file_put_contents($file_location, file_get_contents($image_url));
giữ cho tôi không nhận được lỗi thư mục tệp. Đơn giản fopen
và fwrite
tiếp tục trả về hình ảnh bị hỏng. Điều này làm việc, nhưng nó giữ trở lại tập tin html thay vì tập tin jpg.Lưu hình ảnh từ URL bằng cURL
function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
$imgurl = 'http://some/url/to/image.jpg';
$imagename= basename($imgurl);
if(file_exists('./image/'.$imagename)){continue;}
$image = getimg($imgurl);
file_put_contents('image/'.$imagename,$image);
Thứ gì đó bị thiếu?
Cảm ơn.
Bạn có chắc đó là tệp hình ảnh bạn đang cố gắng tải xuống chứ không phải trang web không? Tệp HTML bạn nhận được là gì? – JJJ