외부이미지 서버에 저장하기 정보
PHP 외부이미지 서버에 저장하기관련링크
본문
데모
<?php
//ver1.0 150409 @_untitle_d
function save_remote_image($url, $save_path)
{
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0); // required
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // required for images
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // maybe redirect on other side?
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'); // or user agent checks?
$data=curl_exec($ch);
curl_close ($ch);
$chars_array = array_merge(range(0,9), range('a','z'), range('A','Z'));
//아래의 문자열이 들어간 파일은 -x 를 붙여서 웹경로를 알더라도 실행을 하지 못하도록 함
$filename = preg_replace("/\.(php|phtm|htm|cgi|pl|exe|jsp|asp|inc)/i", "$0-x", basename($url));
shuffle($chars_array);
$shuffle = implode("", $chars_array);
//첨부파일 첨부시 첨부파일명에 공백이 포함되어 있으면 일부 PC에서 보이지 않거나 다운로드 되지 않는 현상이 있습니다. (길상여의 님 090925)
$change_filename = abs(ip2long($_SERVER[REMOTE_ADDR])).'_'.substr($shuffle,0,8).'_'.str_replace('%', '', urlencode(str_replace(' ', '_', $filename)));
$out_path = $save_path.$change_filename;
if(file_exists($out_path)) @unlink($out_path);
$fp = fopen($out_path,'x');
fwrite($fp, $data);
fclose($fp);
return $change_filename;
}
$url = 'http://i.imgur.com/OJws8NX.png'; //외부이미지
$save_path = $_SERVER[DOCUMENT_ROOT].'/data/remote/'; 타겟폴더
$remote_image = 'http://'.$_SERVER[SERVER_NAME].'/data/remote/'.save_remote_image($url, $save_path);
?>
<img src="<?=$remote_image?>"><br>
<?=$remote_image?>
관련링크
http://untitled.untitle311apyxry1w48.com/pjtecuh
참고
http://stackoverflow.com/questions/7375021/php-retrieve-and-save-remote-image
http://phpschool.com/gnuboard4/bbs/board.php?bo_table=qna_function&wr_id=292925
2