实现简单的图片CDN

   .htaccess文件内容:

   RewriteEngine On

   #RewriteCond %{HTTP_HOST}  ^t.boss.com$
   RewriteCond %{REQUEST_URI}  !^$
   #RewriteCond %{REQUEST_FILENAME}  ^.*\.(jpg|jpeg|png|gif)$  [NC]
   RewriteCond %{REQUEST_FILENAME}  !-d
   RewriteCond %{REQUEST_FILENAME}  !-f
   RewriteRule  ^(.*\.jpg)$   /sync_client.php?url=$1 [NC,QSA,L]

sync_client.php文件内容:

<?php
//var_dump($_GET['url']);
//echo '<img src="http://hazy.allalla.com/inc/logo.jpg">';


$filepath   = empty($_GET['url']) ? exit('no file') : $_GET['url'];
$filepath   = str_ireplace('\'', '', str_ireplace('"', '', $filepath));
$filepath   = str_ireplace('\\', '/', $filepath);
$dir		= dirname($filepath);
$ext		= substr(strrchr( $filepath, '.' ), 1);
if(!in_array($ext, array('jpg', 'jpeg', 'gif', 'png', 'bmp'))) exit('not allow file ext'); 

$domain		= 'http://hazy.voovq.com/';
$url		= $domain . $filepath;

$content    = file_get_contents_($url);
if(strlen($content) < 20) exit('not allow content');

if(!is_dir($dir)) mkdir($dir, 0777, true);

file_put_contents($filepath, $content);

echo '<img src="/' . $filepath . '" />';

//获取URL的内容
function file_get_contents_($url)
{
    if(empty($url)) return false;
	
	$useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19';
	
	if(function_exists('curl_init')) {
    		$ch = curl_init();
    		curl_setopt($ch, CURLOPT_URL, $url);
    		curl_setopt($ch, CURLOPT_TIMEOUT,30);
    		curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$content = curl_exec($ch);
		curl_close($ch);
	}else{
		$content = file_get_content($url);
	}

	return $content;
}

exit;
?>

就这么简单的几句话!放到相应的目录就行了。

300*300
 文章首页关于迷茫时代关于我写意人生
版权所有:迷茫时代 All rights reserved   
执行时间:0.00690 秒