페이지 로딩 속도를 극대화 하는 PHP 파일캐시

2023년 01월 05일
PHP
0 0

//나우호스팅 스마트캐시
function smart_cache ($type,$timeout,$cache_dir,$cache_file,$content=”)
{
//$type = check , run
//$timeput = 캐시파일 유효기간 (초)
//$cache_dir = 캐시파일이 저장될 폴더
//$cache_file = 캐시파일 이름에서
//$content = 캐시파일 저장될 내용

if($type == ‘check’){

//필수입력사항 체크
if(!is_dir($cache_dir)){
echo “캐시파일 저장경로가 올바르지 않습니다.”;
}

if(file_exists($cache_dir.$cache_file)){
//파일이 있으니 파일 만든 시간 가져오기
$cache_file_time = filemtime($cache_dir.$cache_file);
$current_time = time();

        //캐시파일 유효기간 체크후 리턴
if($current_time – $cache_file_time < $timeout){
return true;

}else{
return false;
}
}else{
//파일이 없으니 리턴함
return false;
}
}

//캐시파일 생성
if($type == ‘make’){

$file_handle = fopen($cache_dir.$cache_file,’w’);
fwrite($file_handle,$content);
fclose($file_handle);

}

}

1.위 함수를 어디서든 불러올 수 있는곳에 저장합니다.

2.자신의 홈계정 루트디렉토리에 cache폴더를 생성합니다.

3.아래 코드는 실제 사용 방법입니다.

<?
//캐시구간 시작************************************************************************************
$this_cache_timeout = 600; //600은 10분입니다.
$this_cache_dir = $_SERVER[‘DOCUMENT_ROOT’].’/cache’; // 자신의 홈계정 루트디렉토리에 cache폴더를 생성합니다.
$this_cache_file = ‘main_cache.htm’; //캐시파일 이름(위에 지정한 폴더에 저장됩니다.)

$this_cache_result = smart_cache(‘check’,$this_cache_timeout,$this_cache_dir,$this_cache_file);
if($this_cache_result){
include $this_cache_dir.$this_cache_file;
}else{
ob_start();
//////////////////////////////////////////////////////////////////////////////////////////
//
//
//
//캐시파일 저장할 내용 시작////////////////////////////////////////////////////////////////////////
?>

PHP내용….

<?
//////////////////////////////////////////////////////////////////////////////////////////
//
//
//
//캐시파일 저장할 내용 끝/////////////////////////////////////////////////////////////////////////
$cache_content = ob_get_contents();
ob_end_flush(); 
smart_cache(‘make’,$this_cache_timeout,$this_cache_dir,$this_cache_file,$cache_content);
}
//캐시구간 끝*************************************************************************************
?>

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다