2013-07-25 25 views
1

我正在創建上傳功能,我想上傳一個JSON文件。上傳時檢查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文件'錯誤。

plz幫我看看這段代碼有什麼問題。

+0

那麼,什麼是mimetype? – Blender

+0

你想實現什麼? –

+0

@Blender我不知道,目前我正在本地服務器上工作。 – Jay

回答

2

創建* .json文件時沒有顯式文件類型集。相反,文件MIME類型將是application/octet-stream,這是一個二進制文件,通常是必須在應用程序中打開的應用程序或文檔。

檢查您的陣列$_FILES['uploaded']的類型。

1

沒有「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')