[英]Check JSON file when uploading
我正在创建上传 function,我想上传一个 JSON 文件。
我在文件中的 JSON 字符串是: {"name":"John"}
我的 PHP 代码:
$fileType = $_FILES['uploaded']['type'];
if ($fileType != "application/json") {
print 'Not valid JSON file';
}
也试过:
$fileType = $_FILES['uploaded']['type'];
if ($fileType != "text/json") {
print 'Not valid JSON file';
}
当我尝试上传 JSON 文件时,它显示“JSON 文件无效”错误。
请帮我看看这段代码有什么问题。
创建* .json文件时没有设置明确的文件类型。 相反,文件mime-type将是application/octet-stream
,它是一个二进制文件,通常是必须在应用程序中打开的应用程序或文档。
检查数组$_FILES['uploaded']
的类型。
没有“application / json”之类的东西。 上传后使用file_get_contents()[http://pl1.php.net/manual/en/function.file-get-contents.php]将整个文件读入字符串并使用json_decode()[http://php.net /manual/en/function.json-decode.php],如果它不是真正的json,它将返回null。
$content = file_get_contents($filePath);
$json = json_decode($content, true);
if($json === null) print('Its not a Json! Its a Jacob:P')
这是一个很好的简单的 PHP 脚本,用于在上传时检查 JSON 文件:
// Set maximum file size in bytes
$max_file_size = 1048576; // 1 MB
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Check if the file was uploaded successfully
if (isset($_FILES['json_file']['error']) && $_FILES['json_file']['error'] === UPLOAD_ERR_OK) {
// Get the file information
$file = $_FILES['json_file'];
// Check if the file type is JSON
if ($file['type'] === 'application/json') {
// Check if the file size is less than the maximum file size
if ($file['size'] <= $max_file_size) {
// Read the file content
$file_content = file_get_contents($file['tmp_name']);
// Check if the file content is valid JSON
if (json_decode($file_content) !== null) {
// Move the uploaded file to the desired directory
move_uploaded_file($file['tmp_name'], '/path/to/directory/' . $file['name']);
// Return success message
echo 'The file was uploaded successfully.';
} else {
// Return error message
echo 'The file is not a valid JSON file.';
}
} else {
// Return error message
echo 'The file size exceeds the maximum allowed file size.';
}
} else {
// Return error message
echo 'The file is not a JSON file.';
}
} else {
// Return error message
echo 'There was an error uploading the file.';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.