2016-11-28 33 views
0

使用PHP上傳文件時出現一個問題。我可以成功上傳圖片類型文件,但無法上傳PDF /文檔類型文件。我在下面解釋我的代碼。使用PHP無法上傳文檔/ pdf文件

$target_dir = "../../admin/enquiry/"; 
$fileName = generateRandom() . '_' . $_FILES['attachment']['name']; 
$target_file = $target_dir . basename($fileName); 
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); 
$uploadOk = 1; 
$check = getimagesize($_FILES['attachment']['tmp_name']); 
header('Content-Type: application/json'); 
if ($check !== false) { 
     $result['msg'] = "check not false."; 
      // echo json_encode(array('status' => $check['mime'])); 
     $uploadOk = 1; 
    } else { 
     $result['msg'] = "check false."; 
      // echo json_encode(array('status' => 'upload failed')); 
     $uploadOk = 0; 
    } 

    if (file_exists($target_file)) { 
     echo json_encode(array('status' => 'file already exists')); 
     $uploadOk = 0; 
    } 
    if ($uploadOk == 0) { 
     // 
    } else { 
       if (move_uploaded_file($_FILES['attachment']['tmp_name'], $target_file)) { 
       $result['msg'] = "File has uploaded successfully."; 
       $result['num'] = 1; 
       $result['img'] =$fileName; 
       }else{ 
       $result['msg'] = "Sorry, Your File could not uploaded to the directory."; 
       $result['num'] = 0; 
       } 

      } 

這裏我得到消息check false.意味着有一些問題getimagesize。我也可以傳遞文件大小爲138kb,但在圖片的情況下,它的上傳成功,但其他類型的文件無法上傳,但我需要上傳這些。請幫助我。

+0

打印您的$ _FILES並檢查文件實際上是上傳或任何其他問題?的print_r($ _ FILES);出口; – Ima

+0

@Ima:我已經打印並在那裏收到了這條消息。 – satya

+0

@RuhulAmin:請檢查我對你的帖子的評論。我按你的方式做了,但同樣的問題。 – satya

回答

1

在文件的最頂端,添加這些代碼來啓用php錯誤。

error_reporting(-1); 
ini_set('display_errors', 'On'); 
set_error_handler("var_dump"); 


    $target_dir = "../../admin/enquiry/"; 
    if(isset($_FILES['attachment'])){ 
    $errors= array(); 
    $file_name = generateRandom() . '_' .$_FILES['attachment']['name']; 
    $target_file = $target_dir . basename($file_name); 
    $file_size = $_FILES['attachment']['size']; 
    $file_tmp = $_FILES['attachment']['tmp_name']; 
    $file_type = $_FILES['attachment']['type']; 
    $file_ext=strtolower(end(explode('.',$_FILES['attachment']['name']))); 

    $extension= array("jpeg","jpg","png","pdf"); 

    if(in_array($file_ext,$extension)=== false){ 
     $errors[]="extension not allowed, please choose a JPEG,PNG or PDF file."; 
    } 

    if($file_size > 2097152) { 
     $errors[]='File size must be exactely 2 MB'; 
    } 

    if(empty($errors)==true) { 
     move_uploaded_file($file_tmp,$target_file); 
     echo "Success"; 
    }else{ 
     print_r($errors); 
    } 
    } 
?> 
+0

@拉胡爾:不,它不工作。它再次打印該消息「檢查錯誤」。 – satya

+0

你正在使用'error_reporting(-1)獲得的原始錯誤信息是什麼? ini_set('display_errors','On'); set_error_handler(「var_dump」);' –

0

有條件地調用getImagesize函數。如果文件類型是圖像,那麼它應該得到調用。

+0

@ snehal:我需要允許所有類型的文件。 – satya

0

在調用getimagesize()之前檢查上傳的文件是否爲圖像。

if($file_type=="image/gif" || $file_type=="image/jpeg") 
    { 
     $check = getimagesize($_FILES['attachment']['tmp_name']); 
    } 

也在if-else塊添加條件$check != NULL