Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用ob压缩缓存文件__Php_Apache_Caching - Fatal编程技术网

Php 如何使用ob压缩缓存文件_

Php 如何使用ob压缩缓存文件_,php,apache,caching,Php,Apache,Caching,我正在寻找一种方法来gzip缓存的html副本,并将缓存的版本发送给用户,这可能吗?到目前为止我有这个 //在最前面 $filename = md5($_SERVER['REQUEST_URI']); $cache_file = $_SERVER['DOCUMENT_ROOT'].'/pagecache/' . $filename . '.htm'; $cache_time = 86400; // 24 hours if (file_exists($cache_file) &&am

我正在寻找一种方法来gzip缓存的html副本,并将缓存的版本发送给用户,这可能吗?到目前为止我有这个

//在最前面

$filename   = md5($_SERVER['REQUEST_URI']);
$cache_file = $_SERVER['DOCUMENT_ROOT'].'/pagecache/' . $filename . '.htm';
$cache_time = 86400; // 24 hours

if (file_exists($cache_file) &&
time() - $cache_time < filemtime($cache_file)) {
include($cache_file);
exit;
}
ob_start();

任何指导都将不胜感激

该类缩小和gz html输出

cleaner.php:

<?php  
class Cleaner{
  static function Clean($html){
      $html=preg_replace_callback("~<script(.*?)>(.*?)</script>~si",function($m){
         $m[2]=preg_replace("~//(.*?)\n~si"," ", " ".$m[2]." ");
         return "<script ".$m[1].">".$m[2]."</script>";
      }, $html);
      $search = array(
        "/ +/" => " ",
        "/<!–\{(.*?)\}–>|<!–(.*?)–>|[\t\r\n]|<!–|–>|\/\/ <!–|\/\/ –>|<!\[CDATA\[|\/\/ \]\]>|\]\]>|\/\/\]\]>|\/\/<!\[CDATA\[/" => "");
  //$html = preg_replace(array_keys($search), array_values($search), $html);   
  $search = array(
            "/\/\*(.*?)\*\/|[\t\r\n]/s" => "",
            "/ +\{ +|\{ +| +\{/" => "{",
            "/ +\} +|\} +| +\}/" => "}",
            "/ +: +|: +| +:/" => ":",
            "/ +; +|; +| +;/" => ";",
            "/ +, +|, +| +,/" => ","
       );
       $html = preg_replace(array_keys($search), array_values($search), $html);
       preg_match_all('!(<(?:code|pre|script).*>[^<]+</(?:code|pre|script)>)!',$html,$pre);
       $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!', '#pre#', $html);
       $html = preg_replace('#<!–[^\[].+–>#', '', $html);
       $html = preg_replace('/[\r\n\t]+/', ' ', $html);
       $html = preg_replace('/>[\s]+</', '><', $html);
       $html = preg_replace('/\s+/', ' ', $html);
       if (!empty($pre[0])) {
         foreach ($pre[0] as $tag) {
             $html = preg_replace('!#pre#!', $tag, $html,1);
         }
      }
      return($html);
  }
  static function Cleaning($html) {

         //put cache  checker here


     $html=self::Clean($html);//if you didn't want to minify commented this line
     if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')){
          $html= "\x1f\x8b\x08\x00\x00\x00\x00\x00".
          substr(gzcompress($html, 9), 0, - 4). // substr -4 isn't needed 
          pack('V', crc32($html)).   // crc32 and 
          pack('V', strlen($html));               // size are ignored by all the browsers i have tested 
          header("Content-Encoding: gzip");
          header('Content-Length: ' . strlen($html));
     }


        //you can save your cache 

      return($html);
 }
}?>

您不需要压缩每个文件,在
php.ini
中启用输出压缩并自动完成

zlib.output_compression = On
或使用启动输出缓冲区

ob_start('ob_gzhandler');
现在,如果缓存的目的是因为
速度
存储空间
,那么不要使用文件系统,只要使用Memcached即可。。它支持内置压缩

$memcache = new Memcache();
$memcache->addserver("127.0.0.1");
$memcache->add($filename, ob_get_contents(), MEMCACHE_COMPRESSED);
更新

下面是一个管理文件缓存和memcache的简单脚本。。。您可以轻松地将其扩展到其他类型的存储,如mongoDB或redis

使用文件系统

$storage = new Fcache();
$storage->setDir(__DIR__ . "/cache"); // cache directory
使用Memcache

$storage = new Mcache();
$storage->addserver("127.0.0.1"); // Add Server
你的剧本

$cache = new SimpleCache($storage);
$cache->setTime(5); // 5 sec for demo

if ($data = $cache->get()) {
    echo "Cached Copy <br />\n";
    echo $data;
} else {
    ob_start();
    while(@$i ++ < 10) {
        echo mt_rand();
    }
    $cache->set(ob_get_contents());
    ob_end_flush();
}
储藏

interface CacheStorage {
    public function setTime($time);
    public function read($file);
    public function write($file, $data);
}

// Using Memcache
class Mcache extends Memcache implements CacheStorage {
    private $time = 86400;

    public function setTime($time) {
        $this->time = $time;
    }

    public function read($name) {
        return $this->get($name);
    }

    public function write($name, $data) {
        return $this->add($name, $data, MEMCACHE_COMPRESSED, $this->time);
    }
}

// Using Files System
class Fcache implements CacheStorage {
    private $dir;
    private $time = 86400;

    public function __construct($dir = "cache") {
        $this->setDir($dir);
    }

    public function setDir($dir) {
        $this->dir = $dir;
        if (! is_dir($this->dir) and ! mkdir($this->dir))
            throw new Exception("Invalid Directory");
        $this->dir = $dir;
    }

    public function setTime($time) {
        $this->time = $time;
    }

    public function read($name) {
        $name = $this->dir . "/" . $name;

        if (! is_file($name))
            return false;

        if (time() - filemtime($name) > $this->time)
            return false;

        $zd = gzopen($name, "r");
        $zr = "";
        while(! feof($zd)) {
            $zr .= gzread($zd, 1024);
        }
        gzclose($zd);
        return $zr;
    }

    public function write($name, $data) {
        $name = $this->dir . "/" . $name;
        touch($name);

        $gz = gzopen($name, "w9");
        gzwrite($gz, $data);
        gzclose($gz);
        return true;
    }
}

您的加入不太安全@0xAli valid point+1Wow,谢谢回复。Memcached对我来说是新的,那么我将把您提供的代码放在哪里呢?谢谢:),我删除了我的代码并将你的添加到了标题中,但我得到了一个空白页。请稍候,我将向你提供完整的代码以及如何将其添加到页面中。这太棒了,我将玩一玩并向你汇报。我现在已经将memcached加载到服务器上并进行了测试,运行良好。再说一遍,我真的很感激:)简直太棒了!,仍在测试中,将返回报告。被引导到memcached:)我非常激动。作为一名新手,你们肯定让我大开眼界:)欢迎你们。。。memcached是缓存的好选择。。而且非常非常快。。。
$cache = new SimpleCache($storage);
$cache->setTime(5); // 5 sec for demo

if ($data = $cache->get()) {
    echo "Cached Copy <br />\n";
    echo $data;
} else {
    ob_start();
    while(@$i ++ < 10) {
        echo mt_rand();
    }
    $cache->set(ob_get_contents());
    ob_end_flush();
}
class SimpleCache {
    private $storage;

    function __construct(CacheStorage $storage) {
        $this->storage = $storage;
    }

    public function setTime($time) {
        $this->storage->setTime($time);
    }

    function get() {
        $name = sha1($_SERVER['REQUEST_URI']) . ".cache";
        return $this->storage->read($name);
    }

    function set($content) {
        $name = sha1($_SERVER['REQUEST_URI']) . ".cache";
        $this->storage->write($name, $content);
    }
}
interface CacheStorage {
    public function setTime($time);
    public function read($file);
    public function write($file, $data);
}

// Using Memcache
class Mcache extends Memcache implements CacheStorage {
    private $time = 86400;

    public function setTime($time) {
        $this->time = $time;
    }

    public function read($name) {
        return $this->get($name);
    }

    public function write($name, $data) {
        return $this->add($name, $data, MEMCACHE_COMPRESSED, $this->time);
    }
}

// Using Files System
class Fcache implements CacheStorage {
    private $dir;
    private $time = 86400;

    public function __construct($dir = "cache") {
        $this->setDir($dir);
    }

    public function setDir($dir) {
        $this->dir = $dir;
        if (! is_dir($this->dir) and ! mkdir($this->dir))
            throw new Exception("Invalid Directory");
        $this->dir = $dir;
    }

    public function setTime($time) {
        $this->time = $time;
    }

    public function read($name) {
        $name = $this->dir . "/" . $name;

        if (! is_file($name))
            return false;

        if (time() - filemtime($name) > $this->time)
            return false;

        $zd = gzopen($name, "r");
        $zr = "";
        while(! feof($zd)) {
            $zr .= gzread($zd, 1024);
        }
        gzclose($zd);
        return $zr;
    }

    public function write($name, $data) {
        $name = $this->dir . "/" . $name;
        touch($name);

        $gz = gzopen($name, "w9");
        gzwrite($gz, $data);
        gzclose($gz);
        return true;
    }
}