1

I have the following form that allows user to upload the image:

<form name='form1' method="POST" action="" id="registration_form">
<input type="file" name="data" id="data">
<input type="Submit" name="Upload1" value="Upload1">
</form>

And following php code that does the actual upload:

<?php if(isset($_POST['Upload1']))
{
$errors=array();
$allowed_ext= array('pdf','jpg','jpeg');
$file_name =$_FILES['data']['name']; //error shows in this line
$file_ext = strtolower( end(explode('.',$file_name)));

$file_size=$_FILES['data']['size'];
$file_tmp= $_FILES['data']['tmp_name'];

$type = pathinfo($file_tmp, PATHINFO_EXTENSION);
$data = file_get_contents($file_tmp);

if(in_array($file_ext,$allowed_ext) === false){
    $errors[]='Extension not allowed';
}

if($file_size > 2097152){
    $errors[]= 'File size must be under 2mb';
}
if(empty($errors))
{
   if( move_uploaded_file($file_tmp, 'images/'.$file_name));
   {
    $ct='application/' .$file_ext.'<br/>' ;
    $base64 =  base64_encode($data);        

    //json part is here 
   }
}
else {
    foreach($errors as $error) {
        echo $error , '<br/>'; 
    }
}

}

When I select the file and hit "UPLOAD", it shows error as "Undefined index: data". But what is interesting to note is that 1 out of 10 times, it works! Where am I doing wrong?

Amir Bhandari
  • 117
  • 1
  • 14

1 Answers1

0

According to your form you are not using multiparty/form-data in form tag.

You just need to use

enctype="multipart/form-data" 

Inside the form tag for input type file.

Example:

<form enctype="multipart/form-data">

Why it's needed? Why is form enctype=multipart/form-data required when uploading a file?

If you are using JavaScript for submit the form than you can use formData for getting data from input either post or file.

var formData = new FormData(formId);
Community
  • 1
  • 1
devpro
  • 16,184
  • 3
  • 27
  • 38