0

I have a file input selection as follows in a form which I send data from using the POST Method.

<input type="file" name="inputFile">

I would like to validate that the user has chosen a file and would like to check whether the file is an image file (png,jpg)

I am also getting stuck because a line in my code is generating an error. Why?

'Array key 'inputFile' is undefined'

if (isset($_POST['submit'])) {
   $file = $_FILES['inputFile']; //THIS LINE IS GENERATING AN ERROR
}
GarXik
  • 37
  • 7
  • 2
    https://www.php.net/manual/en/features.file-upload.php, https://www.php.net/manual/en/features.file-upload.post-method.php . Look at the examples and documentation here and make sure you've followed the steps and included what you need. For example, did you make sure to put `enctype="multipart/form-data"` in your form? – ADyson Jun 07 '21 at 13:57
  • You are right. I forgot to include the enctype which was the reason why the key wasn't being passed to the $_FILES global. Thank you. If you want to post it as an answer and maybe improvise on the validation part I would be happy to mark it as solution. – GarXik Jun 07 '21 at 14:04
  • 1
    Not really much need. It's almost certainly a duplicate of many previous questions, neither the enctype thing or how to validate an image are new knowledge or problems, you should be able to google existing examples pretty easily. – ADyson Jun 07 '21 at 14:06

2 Answers2

0

see : https://www.php.net/manual/en/features.file-upload.post-method.php

foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
    // basename() may prevent filesystem traversal attacks;
    // further validation/sanitation of the filename may be appropriate
    $name = basename($_FILES["pictures"]["name"][$key]);
    move_uploaded_file($tmp_name, "data/$name");
}

}

see also: Undefined Array Key error when uploading image on php

it would appear you are looking for $_FILES["inputFile"]["name"] - goodluck

-2

You can use something like:

<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />

And specify the formats you want without PHP

  • server-side validation should always be added as well, for security. Client-side validation adds usability but it's trivial to bypass. It's fine to suggest it, but don't also suggest that OP can forget about validating it in the PHP, that creates a security hole. – ADyson Jun 07 '21 at 14:07
  • As the person above said, I'm looking for a way to do the validation on the server. But thank you anyways. – GarXik Jun 07 '21 at 14:10