1

I have a problem with a file upload form. If I submit the form without uploading any file. It thinks the file was uploaded when it was missing.

if(isset($_FILES["user_image"]))
{
    $extension = explode('.', $_FILES['user_image']['name']);
    $new_name = rand() . '.' . $extension[1];
    $destination = '../upload/' . $new_name;
    move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
    return $new_name;
}
2
  • 1
    By missing do you mean empty file gets updated in the database instead of retaining the old file?
    – fdfdfd
    Nov 29, 2019 at 18:02
  • 1
    It will always be set, you need to make sure that error is not 4 as 4 means "nothing uploaded"
    – zanderwar
    Nov 30, 2019 at 12:51

1 Answer 1

3

you can do this by various ways here is the simplest way to do this

if(isset($_FILES["user_image"]) && (int)$_FILES["user_image"]['error']===0)
{
    $extension = explode('.', $_FILES['user_image']['name']);
    $new_name = rand() . '.' . $extension[1];
    $destination = '../upload/' . $new_name;
    move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
    return $new_name;
}
4
  • How dkes this work? Why does this work? Please edit your answer.
    – Martin
    Nov 30, 2019 at 14:51
  • Please edit your answer and add this explanation. Thanks.
    – Martin
    Nov 30, 2019 at 16:14
  • kindly correct me if I'm wrong if there is no error $_FILES["user_image"]['error'] // return int(0) this element of $_FILE is also returned 0 which is an int why should I use type casting to convert int into int again? while both data types e.g $_FILES["user_image"]['error']==0 // return false int(0)==int(0) //return false both operands of the operator(==)already have the same datatype why should I use Identical(===) operator? Nov 30, 2019 at 16:23
  • no doubt your recommendation is a best practice thanks Nov 30, 2019 at 16:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.