去评论
dz插件网

实现简单的图片CDN

左右不逢缘
2024/02/10 19:13:33
  1. .htaccess文件内容:
  2.    RewriteEngine On
  3.    #RewriteCond %{HTTP_HOST}  ^t.boss.com$
  4.    RewriteCond %{REQUEST_URI}  !^$
  5.    #RewriteCond %{REQUEST_FILENAME}  ^.*\.(jpg|jpeg|png|gif)$  [NC]
  6.    RewriteCond %{REQUEST_FILENAME}  !-d
  7.    RewriteCond %{REQUEST_FILENAME}  !-f
  8.    RewriteRule  ^(.*\.jpg)$   /sync_client.php?url=$1 [NC,QSA,L]
  1. sync_client.php文件内容:
  2. <?php
  3. //var_dump($_GET['url']);
  4. //echo '<img src="http://hazy.allalla.com/inc/logo.jpg">';
  5. $filepath   = empty($_GET['url']) ? exit('no file') : $_GET['url'];
  6. $filepath   = str_ireplace('\'', '', str_ireplace('"', '', $filepath));
  7. $filepath   = str_ireplace('\\', '/', $filepath);
  8. if(!is_file($filepath)){
  9.     $dir        = dirname($filepath);
  10.     $ext        = substr(strrchr( $filepath, '.' ), 1);
  11.     if(!in_array($ext, array('jpg', 'jpeg', 'gif', 'png', 'bmp'))) exit('not allow file ext');
  12.     $domain        = 'http://qqqiushi.com/';[color=#e74c3c]//源站,你的源站必须要允许此站点访问你的图片[/color]
  13.     $url        = $domain . $filepath;
  14.     $content    = file_get_contents_($url);
  15.     if(strlen($content) < 20) exit('not allow content');
  16.     if(!is_dir($dir)) mkdir($dir, 0777, true);
  17.     file_put_contents($filepath, $content);
  18. }
  19. echo '<img src="/' . $filepath . '" />';
  20. //获取URL的内容
  21. function file_get_contents_($url)
  22. {
  23.     if(empty($url)) return false;
  24.    
  25.     $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19';
  26.    
  27.     if(function_exists('curl_init')) {
  28.         $ch = curl_init();
  29.         curl_setopt($ch, CURLOPT_URL, $url);
  30.         curl_setopt($ch, CURLOPT_TIMEOUT,30);
  31.         curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  32.         curl_setopt($ch, CURLOPT_REFERER, $url);
  33.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  34.         curl_setopt($ch, CURLOPT_HEADER, 0);
  35.         $content = curl_exec($ch);
  36.         curl_close($ch);
  37.     }else{
  38.         $content = file_get_contents($url);
  39.     }
  40.     return $content;
  41. }
  42. exit;
  43. ?>
就这么简单的几句话!放到根目录:会自动将图片文件和源站图片文件的目录结构保持一致。