PHP Validation blocking form from sending

时间:2016-04-15 15:02:59

标签: javascript php jquery forms validation

I added a file upload input to a form I have and the PHP validation I added is not allowing the form to send. Whenever I hit the submit button the validation error appears that the file needs to be a .jpeg, jpg, etc. I want this validation, but only if a file has been uploaded.

I am unsure of what to do to make this only check if the file was uploaded and then submitted with the form or ideally catch it before the form is even submitted.

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>

Does anyone know what I can do to get the form to submit, even if the file has not been uploaded?

1 个答案:

答案 0 :(得分:2)

You can check the UPLOAD_ERR_NO_FILE constant instead of doing isset():

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

The problem with your isset() is that $_FILES['file'] will be set (but with an error code), even if the user didn't select a file.