Question

Im having problems with form validation. When I dont select a file for upload I still get an error that promts only png images valid. I thought that if no file was selected the $_FILES array would be empty.

What am I doing wrong?

my html form excerpt for file upload looks like this:

<label for="file">Filename
<span class="small">Upload image</span>
</label>
<input type="file" name="file" id="file">

my php processing looks like this:

 $submitted_file = $_FILES['file'];

 if(isset($submitted_file)) {

    // verify the file PNG only
    $fileType = exif_imagetype($submitted_file["tmp_name"]);
    $allowed = array(IMAGETYPE_PNG);
    $max_filesize = 512000;

    if (!in_array($fileType, $allowed)) {
    $proceed = false;
    $arrErrors['submitted_file_ext'] = 'Please upload .png images only.';
    }
}
Was it helpful?

Solution

The array that you are checking should have the field ["tmp_name"] as null if it is blank. Try this code instead:

if(!empty($submitted_file["tmp_name"])) {

OTHER TIPS

The right way is to check $_FILES['error']

if ($_FILES['name']['error'] === UPLOAD_ERR_OK) {
    // file successfully uploaded
}

More info here http://ru2.php.net/manual/en/features.file-upload.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top