我在将数据添加到现有JSON文件时遇到了问题。脚本第一次运行时它都可以工作,但第二次文件已经存在时,JSON文件会更新,但值为NULL。
PHP for UPLOADING:
$ds = DIRECTORY_SEPARATOR;
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 10097152){
$errors[]='File size must be less than 10 MB';
}
if(empty($errors)==true){
$dirPath = $ds .'hidden' . $ds .$_SESSION['user']['username']. date('d-m-Y-H-i-s'). $ds;
$result = mkdir($dirPath, 0770, true);
move_uploaded_file($file_tmp, $dirPath.$file_name);
save_document_info_json($file);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
JSON SAVING FILE
function save_document_info_json($file){
$ds = DIRECTORY_SEPARATOR;
$jsonfile = UPLOADEDFILES."docinfo.json";
if(is_file($jsonfile)){
$jsonText = file_get_contents($jsonfile);
$workflow = json_decode($jsonText, true);
} else{
$jsonText = '{"statistics": {"total": 0, "approved": 0}, "fileInfo":[]}';
$workflow = json_decode($jsonText, true);
}
for ($i = 0; $i <= count($workflow["fileInfo"]); ++$i){
$filename = $_FILES['files']['name'][$i];
$filesize = $_FILES['files']['size'][$i];
$filetype = $_FILES['files']['type'][$i];
}
$fileInfo["status"] = "pending";
$fileInfo["submittedBy"] = $_SESSION['user']['username'];
$fileInfo["approvedBy"] = "";
$fileInfo["fileName"] = $filename;
$fileInfo["location"] = $ds .'hidden' . $ds .$_SESSION['user']['username']. date('d-m-Y-H-i-s'). $ds;
$fileInfo["fileType"] = $filetype;
$fileInfo["size"] = $filesize;
array_push($workflow["fileInfo"], $fileInfo);
$total = count($workflow["fileInfo"]);
$workflow["statistics"]["total"] = $total;
file_put_contents($jsonfile, json_encode($workflow));
}