php 镜像 bootcdn 静态资源示例
<?php
error_reporting(0);
$main = new Main();
$main->libs();
Class Main{
private $libDir = __DIR__.'/'; // 静态资源保存目录
private $host = 'https://cdn.bootcdn.net'; // 镜像站点
public function libs(){
$url = $_SERVER['REQUEST_URI'];
$this->header($url);
$url_array = explode('?',$url); $url = $url_array['0']; // 处理文件版本号 适应自己上传的静态资源
if(is_file($this->libDir.$url)){
if(count(explode('.php',$url)) > 1){
http_response_code(403); // 屏蔽下载php文件
}else{
echo file_get_contents($this->libDir.$url);
}
}else{
$new_url = $this->host.$url;
$data = $this->request($new_url);
if($data['headers']['http_code'] == 200 && strlen($data['output']) > 10){
$this->writeFile($url, $data['output']);
echo $data['output'];
}else{
header('HTTP/1.1 404 Not Found');
}
}
}
// 写入文件 去掉首尾 得到需要创建的目录 依次检查并创建 再写入
private function writeFile($url, $data){
$url_array = explode('/', $url);
array_shift($url_array); $file_name = array_pop($url_array); $new_v = '';
$file_name_array = explode('?',$file_name); $file_name = $file_name_array['0']; // 处理文件版本号
foreach ($url_array as $k => $v) {
$new_v = $new_v.'/'.$v;
if(!is_dir($this->libDir.$new_v)){ mkdir($this->libDir.$new_v); }
}
return file_put_contents($this->libDir.$new_v.'/'.$file_name,$data);
}
private function header($url){
ob_end_clean();
$url = explode('?',$url); // 处理文件版本号
$url_array = explode('.', $url[0]);
$name = $url_array[count($url_array)-1];
switch ($name) {
case 'css':
header('Content-type: text/css');
break;
case 'js':
header('Content-type: text/javascript');
break;
case 'png':
header('Content-Type: image/jpeg');
break;
case 'gif':
header('Content-Type: image/jpeg');
break;
default:
header('Content-Type: application/octet-stream');
break;
}
}
// 发起请求
private function request($Url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'GET');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$output = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return ['headers' => $headers, 'output' => $output];
}
}