How to pass a callback function with parameters for ob_start in PHP?

I followed this tutorial on the caching function. I ran into the problem of passing a callback function cache_page()to ob_start. How to pass cache_page()along with two parameters $midand $pathon ob_start, something along the lines

  ob_start("cache_page($mid,$path)");

Of course, the above will not work. Here is a sample code:

$mid = $_GET['mid'];

$path = "cacheFile";

define('CACHE_TIME', 12);

function cache_file($p,$m)
{
    return "directory/{$p}/{$m}.html";
}

function cache_display($p,$m)
{
    $file = cache_file($p,$m);

    // check that cache file exists and is not too old
    if(!file_exists($file)) return;

    if(filemtime($file) < time() - CACHE_TIME * 3600) return;

    header('Content-Encoding: gzip');

    // if so, display cache file and stop processing
    echo gzuncompress(file_get_contents($file));

    exit;
}

  // write to cache file
function cache_page($content,$p,$m)
{
  if(false !== ($f = @fopen(cache_file($p,$m), 'w'))) {
      fwrite($f, gzcompress($content)); 
      fclose($f);
  }
  return $content;
}

cache_display($path,$mid);

ob_start("cache_page"); ///// here the problem
+4
source share
1 answer

The signature of the callback to ob_startshould be :

string handler ( string $buffer [, int $phase ] )

Your method cache_pagehas an incompatible signature:

cache_page($content, $p, $m)

, ($p $m), ob_start . ob_start . $p $m.

, .

function cache_file()
{
    return CACHE_PATH . md5($_SERVER['REQUEST_URI']);
}

, , . :

$p = 'cache';
$m = 'foo';

ob_start(function($buffer) use ($p, $m) {
    return cache_page($buffer, $p, $m);
});

ob_start, cache_page $p $m .

+4

Source: https://habr.com/ru/post/1584606/


All Articles