php app接口开发-2
Posted bkwxx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php app接口开发-2相关的知识,希望对你有一定的参考价值。
创建fiel.php
1 <?php 2 3 class File { 4 private $_dir; 5 6 const EXT = ‘.txt‘; 7 8 public function __construct() { 9 $this->_dir = dirname(__FILE__) . ‘/files/‘; 10 } 11 public function cacheData($key, $value = ‘‘, $cacheTime = 0) { 12 $filename = $this->_dir . $key . self::EXT; 13 14 if($value !== ‘‘) { // 将value值写入缓存 15 if(is_null($value)) { 16 return @unlink($filename); 17 } 18 $dir = dirname($filename); 19 if(!is_dir($dir)) { 20 mkdir($dir, 0777); 21 } 22 23 $cacheTime = sprintf(‘%011d‘, $cacheTime); 24 return file_put_contents($filename,$cacheTime . json_encode($value)); 25 } 26 27 if(!is_file($filename)) { 28 return FALSE; 29 } 30 $contents = file_get_contents($filename); 31 $cacheTime = (int)substr($contents, 0 ,11); 32 $value = substr($contents, 11); 33 if($cacheTime !=0 && ($cacheTime + filemtime($filename) < time())) { 34 unlink($filename); 35 return FALSE; 36 } 37 return json_decode($value, true); 38 39 } 40 } 41 42 $file = new File(); 43 44 echo $file->cacheData(‘test1‘);
通过test.php调用file.php,访问app_api.com/test.php
1 <?php 2 require_once("./file.php"); 3 $data = array( 4 "name" => "bk", 5 "age" => 25 6 ); 7 $file = new File(); 8 if($file->cacheData("index_mk_cache",$data)){ 9 echo "success"; 10 }else{ 11 echo "error"; 12 }
以上是关于php app接口开发-2的主要内容,如果未能解决你的问题,请参考以下文章