0

I have a website which makes api calls. I have 5 apis to process. Currently my php script makes one on one api call which makes too slow to load my website (more than 1 min almost). To takle this I had to cache the response from api calls. I had tried

    <?php
function getUrl () {
    if (!isset($_SERVER['REQUEST_URI'])) {
    $url = $_SERVER['REQUEST_URI'];
    } else {
    $url = $_SERVER['SCRIPT_NAME'];
    $url .= (!empty($_SERVER['QUERY_STRING']))? '?' . $_SERVER[ 'QUERY_STRING' ] : '';

    }
    return $url;
}

//getUrl gets the queried page with query string
function cache ($buffer) { //page's content is $buffer
    $url = getUrl();
    $filename = md5($url) . '.cache';
    $data = time() . '¦' . $buffer;
    $filew = fopen("cache/" . $filename, 'w');
    fwrite($filew, $data);
    fclose($filew);
    return $buffer;
}

function display () {
    $url = getUrl();
    $filename = md5($url) . '.cache';
    if (!file_exists("/cache/" . $filename)) {
    return false;
    }
    $filer = fopen("cache/" . $filename, 'r');
    $data = fread($filer, filesize("cache/" . $filename));
    fclose($filer);
    $content = explode('¦', $data, 2);
    if (count($content)!= 2 OR !is_numeric($content['0'])) {
        return false;
    }
    if (time()-(100) > $content['0']) { // 100 is the cache time here!!!
        return false;
    }
        echo $content['1'];
        die();
}

// Display cache (if any)
display();  // if it is displayed, die function will end the program here.

// if no cache, callback cache
ob_start ('cache');
?>

I got this script from "Automatically create cache file with php" in stack-overflow. After implementing this script, my website works well with loading speed under 30 sec which is fine. However, my website has query parameters like &p=a&q=b. These parameters are loading from a cached version from the above script which are not updated according to the request. The above script caches the cache which is old and implements that version. It is not updating with my new parameters which are changing every time according to the user. The user need to pass the date which changes from day to day. The cache script loads yesterday's date. I haven't made cache which my static files like js files, css too.

Any suggestions?

Community
  • 1
  • 1
abdul riyaz
  • 80
  • 1
  • 1
  • 10
  • Possible duplicate of [Fatal error: Maximum execution time of 30 seconds exceeded](http://stackoverflow.com/questions/5164930/fatal-error-maximum-execution-time-of-30-seconds-exceeded) – Gal Sisso Feb 09 '16 at 08:34
  • Results will be displayed on webpage after 1min, no errors!. i want to cache it. – abdul riyaz Feb 09 '16 at 08:37

0 Answers0