2016-04-15 74 views
2

我添加了一個文件上傳輸入到我有一個表單,我添加的PHP驗證不允許表單發送。每當我點擊提交按鈕時,出現驗證錯誤,該文件需要是一個.jpeg,jpg等。我想這個驗證,但只有當一個文件已經上傳。PHP驗證阻止發送表單

我不知道該怎麼做才能檢查文件是否已經上傳,然後用表單提交,或者在表單提交之前理想地捕獲它。

if(isset($_FILES['file'])) { 
    $file = $_FILES['file']; 

    //File properties 
    $file_name = $file['name']; 
    $file_tmp = $file['tmp_name']; 
    $file_size = $file['size']; 
    $file_error = $file['error']; 

    //File Extension 
    $file_ext = explode('.', $file_name); 
    $file_ext = strtolower(end($file_ext)); 

    $allowed = array('txt', 'jpg', 'jpeg', 'png'); 

    if(in_array($file_ext, $allowed)) { 
     if($file_error === 0) { 
      if($file_size <= 2097152) { 
       $file_name_new = uniqid('', true) . '.' . $file_ext; 


      } else { 
       echo "Sorry, your file is WAY too large"; 
      } 
     } 
    } else { 
     echo "Sorry, only JPG, JPEG, PNG and TXT files are allowed."; 
    } 
} 

<form action="" autocomplete="on" method="POST" id="project-information-form" enctype="multipart/form-data"> 
    <input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple> 
    <label for="file"><span id="file-upload-image"><img src="/icons/white-upload.png" height="25px" width="25px"></span>File Upload</label> 
    <input type="submit" id="submit-project" class="submit-project-button" value="Send Project Inquiry"> 
</form> 

有沒有人知道我可以做什麼來獲取表單提交,即使該文件尚未上傳?

+0

看看[這個線程](http://stackoverflow.com/questions/2958167/how-to-test-if-a-user-has-se- ies-to-file-to-upload)。 –

回答

2

您可以檢查的,而不是做isset()UPLOAD_ERR_NO_FILE常數:

if($_SERVER['REQUEST_METHOD'] == 'POST'){ 
    if($_FILES['file']['error'] != UPLOAD_ERR_NO_FILE) { 
     // an upload was attempted 

的問題與您isset()$_FILES['file']將被設置(但有錯誤代碼),即使用戶沒有選擇文件。

+0

但是爲什麼總是這樣設置? – Becky

+0

其實這並沒有奏效。它現在不斷顯示錯誤消息,甚至不等待提交按鈕被按下。 – Becky

+0

感謝您的幫助! – Becky