0

I have a PHP validate statement for a file upload on a HTML form. It has errors that are printed if the file is not an image or if the file extension isn't supported. The if statement states that if $_FILES is empty to validate it, and show up the appropriate errors. The problem is that although the file upload is not a required input, the error message "file does not seem to be an image" shows up even if the $_FILES variable is empty? Can someone please help

error_reporting (E_ALL ^ E_NOTICE);

if($_FILES != "") // [START FILE UPLOADED]
{
    include 'image_validate.php';

    $file = $_FILES['eventPhoto'];

    $file_name = $file['name'];

    $error = ''; // Empty

    // Get File Extension (if any)
    $ext = strtolower(substr(strrchr($file_name, "."), 1));

    // Check for a correct extension. The image file hasn't an extension? Add one
    if($validation_type == 1)
    {
        $file_info = getimagesize($_FILES['eventPhoto']['tmp_name']);

        if(empty($file_info)) // No Image?
        {
            $error .= "<br/><div class='submitEventErrors'>The uploaded file doesn't seem to be an image.</div><br/>";
        }
        else // An Image?
        {
            $file_mime = $file_info['mime'];

            if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
            {
                $extension = $ext;
            }
            else
            {
                $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
            }

            if(!$extension)
            {
                $extension = '';
                $file_name = str_replace('.', '', $file_name);
            }
        }
    }

    else if($validation_type == 2)
    {
        if(!in_array($ext, $image_extensions_allowed))
        {
            $exts = implode(', ',$image_extensions_allowed);
            $error .= "<br/><div class='submitEventErrors'>You must upload a file with one of the following extensions: ".$exts."</div>";
        }

        $extension = $ext;
    }

    if($error)
    {
        echo '<font color="red">'.$error.'</font>';
    }

    if($error == "") // No errors were found?
    {
        $new_file_name = strtolower($file_name);
        $new_file_name = str_replace(' ', '-', $new_file_name);
        $new_file_name = substr($new_file_name, 0, -strlen($ext));
        $new_file_name .= $extension;

    }
    else
    {
        @unlink($file['tmp_name']);
    }

} // [END FILE UPLOADED]

1 Answer 1

1

Try using is_uploaded_file instead of if($_FILES != "")

More details here http://php.net/manual/en/function.is-uploaded-file.php

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

Comments

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.