2

I made a form at HTML with an option to upload an image. The problem is that when I check the $_FILES array at the php code, it is not found.

The HTML form:

<form method="POST" action="addProduct.php" onsubmit="return checkValidation()"> 
Image(optional): <input type="file" name="fileImg" accept="image/*" id="fileImg">
<input id="submitProduct" type="submit" name="submitBtn" value="Submit product" onclick="checkValidation()"/>
</form>

The checkValidation() function:

function checkValidation(){
    var regex = /\.(jpg|JGP|jpeg|JPEG|png|PNG|gif|GIF)$/;
    if (($('#fileImg').val()) && (!(regex.test($('#fileImg').val()))))
    {
        return false;
    }
}

And the php code:

if(isset($_POST["submitBtn"])){
    if(!(empty($_FILES)))
    {
        if (file_exists('uploads/'.$_FILES["fileImg"]["name"]))
        {
            echo $_FILES["fileImg"]["name"]." already exists. ";
        }
        else
        {
            move_uploaded_file($_FILES["fileImg"]["tmp_name"], 'uploads/'. $_FILES["fileImg"]["name"]);
            $path = $_FILES["fileImg"]["name"];
        }
    }
    else
        $path = 'no_photo.jpg';

The problem is that at the php code, it always jumps to the else branch (which gives me some default image).

Thanks in advance.

Guy Krief
  • 41
  • 9

1 Answers1

1

Your form lacks the enctype='multipart/form-data' attribute. Without it, $_FILES would always be empty.

Read more about it here: What does enctype='multipart/form-data' mean?

Community
  • 1
  • 1
Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292
  • sorry, stupid question. I put it in the form and it worked. Thanks a lot! – Guy Krief Aug 16 '13 at 22:26
  • @ErumHannan If you have a *new* question, please ask it by clicking the [Ask Question](http://stackoverflow.com/questions/ask) button. If you have sufficient reputation, [you may upvote](http://stackoverflow.com/privileges/vote-up) the question. Alternatively, "star" this question as a favorite and you will be notified of any new answers. – user May 28 '14 at 11:51