Skip to content

Instantly share code, notes, and snippets.

@KennethanCeyer
Last active September 24, 2015 17:12
Show Gist options
  • Save KennethanCeyer/66d49cb8faf790dc77b1 to your computer and use it in GitHub Desktop.
Save KennethanCeyer/66d49cb8faf790dc77b1 to your computer and use it in GitHub Desktop.
Parsing og:image meta data and download image file to your server.
<?php
// 해당 소스는 curl을 사용하기 때문에, 서버에서 PHP Curl extension을 사용할 수 있어야 합니다.
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $LinkView['link_url']);
// $LinkView['link_url']에 원하는 대상 페이지 주소를 넣어주세요.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
// $content에 대상 HTML 페이지를 가지고 왔습니다.
$dom_obj = new DOMDocument();
@$dom_obj->loadHTML($contents);
// Document 파싱을 위해 DOMDocument 객체를 생성.
$meta_val = null;
if(count($dom_obj) > 0) {
try {
foreach($dom_obj->getElementsByTagName('meta') as $meta) {
if($meta->getAttribute('property')=='og:image'){
// og:image를 찾아서 meta_val에 저장했습니다.
$meta_val = $meta->getAttribute('content');
break;
}
}
} catch(Exception $e) { ; }
}
if(!empty($meta_val)) {
// meta_val가 empty면 og:image가 없는 상태이니 분기를 사용합니다.
$ext = substr(strrchr($meta_val, '.'), 1);
// og:image의 확장자를 찾습니다.
if(in_array($ext, array ('jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'))) {
// 허용 확장자만을 다운로드 합니다.
$local = $this->config->item('ward_image_path') . '/' . 'wardimg-' . time() . '.' . $ext;
// wardimg-[시간 값].[확장자] 형태로 해당 이미지를 저장합니다.
// 이 부분 설정을 바꿔주셔야 합니다. (서버 저장위치/이미지 이름)
$src = APPPATH . '..' . $local;
$fp = fopen ($src, 'w+');
// 해당 위치에 파일을 읽기형태로 열고 이미지를 씁니다.
$ch = curl_init($meta_val);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_exec($ch);
curl_close($ch);
fclose($fp);
// 대상 서버에서 이미지를 가지고 오기 위해 curl을 설정합니다.
if(file_exists($src)) {
// do somthing!
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment