将JSON数据存储在临时文件中,并在24小时后删除?

时间:2019-03-14 06:44:51

标签: php json apache

如何在Apache服务器上临时存储JSON数据。 JSON中有一些用户信息。如果文件本身每隔24小时删除一次,那就太好了。

$json_array = array(); 
 while($row = mysqli_fetch_assoc($result)) 
 { 
 $json_array[] = $row; 
 } 

 $final_array = json_encode($json_array);

如此,我创建了JSON文件,也可以将其存储在.json文件中,但是我如何创建包含此数据的临时文件。而且该文件只能从服务器读取。

2 个答案:

答案 0 :(得分:0)

你为什么这么想? 为什么不尝试php会话或cookie 24小时或浏览器js localStorage?

如果需要Temp文件,请使用php-Apache文件创建和写入方法在Apache服务器中创建文件,并在24小时后使用Cron Job删除该文件

答案 1 :(得分:0)

使用file_put_contents存储数据,但是为每个用户创建一些前缀,因此您可以拥有单独的文件,然后在以下位置进行检索:

 $json_array = array(); 
 while($row = mysqli_fetch_assoc($result)) 
 { 
 $json_array[] = $row; 
 } 

 $final_array = json_encode($json_array);
 $generatedName = 'userIDprefix_userData' .  '.json'; //replace userIDprefix with user ID, this way we can use prefix to store different files per user, and retrieve file for user
 //use file put contents to store data 
 file_put_contents('path/to/json/data/' . $generatedName , $final_array);

使用file_get_contents()来检索文件数据:

 $generatedName = 'userIDprefix_userData' .  '.json'; //replace userIDprefix with user ID, this way we can use prefix to store different files per user, and retrieve file for user
 //use file put contents to store data 
 $userJSONData = file_get_contents('path/to/json/data/' . $generatedName );

然后将cron设置为每5分钟运行一次,请使用globfilemtime扫描存储数据的目录,并使用filemtime获取文件的时间戳,以便与当前日期,如果早于24h,则将其删除

$past24hours = strtotime('-24 hours');
foreach (glob("path/to/json/data/*.json") as $filename) {
   if( filemtime($filename) < $past24hours ){
     unlink($filename);
    }
}

设置cron以执行文件,其中每10分钟运行一次要删除json文件的脚本:

*/10 * * * * /usr/bin/php /path/to/script/to/delete-json.php

注意:

请勿将此文件夹的权限设置为777,至少为775,甚至是755。 另外,为防止直接访问.json文件,请在该文件夹中至少放置空白index.php和带有内容的.htaccess:

#forbid access to folders and to files  
 RewriteEngine on 
 RewriteRule \.(json|txt)$ - [F] 
 deny from all