2

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
  • Take a look at this thread. Commented Apr 15, 2016 at 15:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Why would it always be set, though?
Actually this didn't work. It is constantly displaying the error message now and not even waiting for the submit button to be pressed.
Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.