0

我的网站正在正确缓存指定文件夹中的所有文件,但是这些文件夹中存储的文件太多。我正在考虑将缓存文件夹拆分为包含文件名第一个字母的子目录,然后可能从那里进一步分解。

如下所示,压缩版本保存在“gz”文件夹中,常规缓存存储在“html2”文件夹中。

代码:

if ( $cache ) {
#header("Content-Type: text/html");
// get the buffer
$buffer = ob_get_contents();
#$length = ob_get_length();
#header('Content-Length: '.$length);
// end output buffering, the buffer content
// is sent to the client
ob_end_flush();

// now we create the cache file
if (!file_exists($pathName)) {
    mkdir($pathName, 0755, true);
}
if (!file_exists(str_replace('/html/html2/', '/html/gz/', $pathName))) {
    mkdir(str_replace('/html/html2/', '/html/gz/', $pathName), 0755, true);
}
$compressed = preg_replace('%<!--(.|\s)*?-->%', '', $buffer);
$compressed = sanitize_output($compressed);
$encoded = gzencode($compressed, 9);
file_put_contents($file, $compressed);
file_put_contents(str_replace('/html/html2/', '/html/gz/', str_replace('.html', '.gz', $file)), $encoded);

}

根据上面的代码,这里是当前缓存文件的路径:

/html2/New-York-Hotels.html

/gz/New-York-Hotels.gz

理想情况下,我希望缓存的文件位置如下所示:

/html2/N/New-York-Hotels.html

/gz/N/New-York-Hotels.gz

非常感谢您的帮助!提前致谢。

4

1 回答 1

1

试试这个代码(固定):

if ($cache) {

  // Get the buffer into a string
  // I do it this way to save memory - no point in keeping 2 copies of the data
  $buffer = ob_get_clean();

  // Send buffer content to the client
  // header("Content-Type: text/html");
  // header('Content-Length: '.strlen($buffer));
  echo $buffer;
  flush();

  // Get the paths into sensibly named variables
  $fileBase = basename($file); // The name of the HTML file
  $htmlPath = rtrim($pathName, '/').'/'.strtoupper($fileBase[0]).'/'; // The directory the HTML file is stored in
  $gzPath = str_replace('/html/html2/', '/html/gz/', $htmlPath); // The directory the gzipped file is stored in
  $htmlFile = $htmlPath.$fileBase; // The full path of the HTML file
  $gzFile = $gzPath.str_replace('.html', '.gz', $fileBase); // The full path of the gzipped file

  // Make sure the paths exist
  if (!is_dir($htmlPath)) {
    mkdir($htmlPath, 0755, true);
  }
  if (!is_dir($gzPath)) {
    mkdir($gzPath, 0755, true);
  }

  // Strip comments out of the file and sanitize_output() (whatever than does)
  // $compressed is a silly name for a variable when we are also zipping the data
  $html = sanitize_output(preg_replace('%<!--(.|\s)*?-->%', '', $buffer));

  // Save the files
  file_put_contents($htmlFile, $html);
  file_put_contents($gzFile, gzencode($html, 9));

}

这里应该处理几个未经检查的潜在错误,例如如果mkdir()失败会发生什么,如果file_put_contents()失败会发生什么?

于 2012-08-08T15:14:25.847 回答