PHP 快速搭建镜像站

Apache 的配置就略了,可以参照其它文章,本文直接从有可用的 php 目录环境开始了。

修改 .htaccess

简单来说,htaccess文件是Apache服务器中的一个配置文件,它负责相关目录下的网页配置。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?s=$1 [QSA,PT,L]

这样就可以将所有的请求跳转到 index.php 了,接下来编辑 index.php。

修改 index.php

我们以 baidu.com 为例,其它地址按需修改就可以了:

<?php
$url = 'https://www.baidu.com';
$path = isset($_GET['s']) ? strval($_GET['s']) : '/';

$tmp = 'temp/'.base64_encode($path);
if(!file_exists($tmp)) {
    $geturl = $url.'/'.ltrim($path, '/');

    $content = file_get_contents($geturl);
    $content = str_replace($url,'',$content);

    $writer = fopen($tmp, "w");
    fwrite($writer, $content);
    fclose($writer);
}

echo readfile($tmp);
?>

顺便加了个文件缓存,加速一下访问速度,然后只要定时清理缓存文件就可以了。

缓存清理

附一个缓存清理的 cron.php 脚本,定时调用就可以了:

<?php
/*
 * 删除文件夹下$n分钟前创建的文件
 * @param $dir 要处理的目录,物理路径,结尾不加\
 * @param $n 过期时间,单位为分钟
 * @return void
 */
function z_del_file_by_ctime($dir,$n){
    if(is_dir($dir)){
        if($dh=opendir($dir)){
            while (false !== ($file = readdir($dh))){
                if($file!="." && $file!=".."){
                    $fullpath=$dir."/".$file;
                    if(!is_dir($fullpath)){ 
                        $filedate=filemtime($fullpath);
                        $minutes=round((time()-$filedate)/60);
                        if($minutes>$n)
                            unlink($fullpath); //删除文件
                    }
                }
            }
        }
        closedir($dh);
    }
}

$dir = realpath('./temp');
z_del_file_by_ctime($dir, 60);
?>

All Done !

至此结束,测试访问一下正常可用。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注