facebook twitter hatena line email

Php/codeigniter/cache

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

準備

application/api/config/config.php

$config['cache_path'] = APPPATH . 'cache/';

指定urlのhtmlキャッシュ

class Cache extends CI_Controller {
    public function index()
    {
        echo $this->config->item('cache_path');
        $url = "https://www.yahoo.co.jp/";
        echo $this->get_cached_html($url, "yahoo");
        exit;
    }
    function get_cached_html($url, $cache_key, $ttl = 86400)
    {
        $this->load->driver('cache', array('adapter' => 'file'));

        // キャッシュから取得
        $cached_data = $this->cache->get($cache_key);
        if ($cached_data !== FALSE)
        {
            return $cached_data;
        }

        // htmlをダウンロード
        $html = file_get_contents($url);
        if ($html === FALSE)
        {
            log_message('error', 'htmlのダウンロードに失敗: ' . $url);
            return FALSE;
        }

        // キャッシュに保存
        $this->cache->save($cache_key, $html, $ttl);
        return $html;
    }
}