PHP URL에서 PC로 이미지를 저장해야 합니다.예를 들어 페이지가 있다고 칩시다.http://example.com/image.php
하나의 “꽃” 이미지를 가지고 있고, 다른 것은 없습니다.이 이미지를 URL에서 (PHP를 사용하여) 새 이름으로 저장하려면 어떻게 해야 합니까?
질문에 대한 답변
가지고 계신 경우allow_url_fopen
로 설정하다.true
:
$url = 'http://example.com/image.php'; $img = '/my/folder/flower.gif'; file_put_contents($img, file_get_contents($url));
그렇지 않으면 cURL을 사용합니다.
$ch = curl_init('http://example.com/image.php'); $fp = fopen('/my/folder/flower.gif', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp);
copy('http://example.com/image.php', 'local/folder/flower.jpg');
주의: 여기에는 allow_url_fopen이 필요합니다.
$content = file_get_contents('http://example.com/image.php'); file_put_contents('/my/folder/flower.jpg', $content);
발텍의 cURL 답변은 나에게 맞지 않았다.네, 제 특정 문제로 인해 약간 개선되었습니다.
예.,
서버에 리다이렉트가 있는 경우(페이스북프로파일 이미지를 저장하려고 하는 경우 등), 다음의 옵션을 설정할 필요가 있습니다.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
완전한 솔루션은 다음과 같습니다.
$ch = curl_init('http://example.com/image.php'); $fp = fopen('/my/folder/flower.gif', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp);
이 예에서는 리모트이미지를 image.jpg에 저장합니다.
function save_image($inPath,$outPath) { //Download images from remote server $in= fopen($inPath, "rb"); $out= fopen($outPath, "wb"); while ($chunk = fread($in,8192)) { fwrite($out, $chunk, 8192); } fclose($in); fclose($out); } save_image('http://www.someimagesite.com/img.jpg','image.jpg');