How to dynamically write an array into a PHP file as a file cache

 

/**
* @Purpose: Set cache file information
* @Method Name:set_user_capacityCache()
* @Parameter: int $uid user's uid, array $arr data array stored
* @Return: Return the character length of the stored file
*/
function set_user_capacityCache($uid, $arr){
	$objfile = get_user_capacityCache_path($uid);
	$arrays = array();
	if(file_exists($objfile)){
		$arrays = file_get_contents($objfile);
                $arrays = unserialize($arrays);
		if(!is_array($arrays))
			$arrays = array();
	}
	$arrays[$uid] = $arr;
        $data = serialize($arrays);
	$strlen = file_put_contents($objfile, $data, LOCK_EX);
	chmod($objfile, 0777);
	return $strlen;
}
/**
* @Purpose: If the cached file exists, take the cached content, if it does not exist, return false
* @Method Name:output_user_capacityCache()
* @Parameter: int $uid User's uid
* @Return: exists and returns array data does not exist and returns false
*/
function output_user_capacityCache($uid)
{
	$objfile = get_user_capacityCache_path($uid);
	if(!file_exists($objfile))
        {
	    return false;
	}
        else
        {
            $arrays = file_get_contents($objfile);
            $arrays = unserialize($arrays);
	    if(!is_array($arrays) || empty($arrays[$uid]) || ($arrays[$uid]['timestamp'] + 24*3600 < time()))
		return false;
	    return $arrays[$uid];
	}
}
/**
* @Purpose: Get the path of the ability market information file
* @Method Name:  get_user_headCache_path()
* @Parameter: int $uid User's uid
* @Return: string returns the path of the file
*/
function get_user_capacityCache_path($uid)
{
	$dir = __DIR__;//Directory
	$folder_name = ceil($uid/10000); //Folder name
	$file_name = ceil($uid/100).'.php'; //file name
	
	$folder_dir = $dir.$folder_name."/";
	$file_path = $folder_dir.$file_name;
	
	if(!is_dir($folder_dir))
	    mkdir ($ folder_dir, 0777, true);

	return $file_path;
}

 

 Note: Only arrays can be stored, objects cannot be stored.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326491638&siteId=291194637