Question

getting this error how can i fix it?. i just need point in the right direction

Notice: Undefined index: file_upload in C:\Users\chisenga\Documents\project\htdocs\project\upload.php on line 36

this is the code

 form method="post" enctype="multipart/form-data" action="upload.php">
<label for="">File: <input type="file" name="file_upload"/></label>
<input type="submit" value="Upload"/>
</form>


<?php

$file = $_FILES['file_upload'];
$name = $file['name'];
$type = $file['type'];
$tmp_location = $file['tmp_name'];
$upload = 'uploads';
$final_destination = $upload.'/'.$name;
$error = $file['error'];
$max_upload_size = 2097152;
$size = $file['size'];


$allowedImageTypes = array( 'image/png', 'image/jpeg', 'image/gif' );

function imageTypeAllowed($imageType){
global $allowedImageTypes;
if(in_array($imageType, $allowedImageTypes)){
    return true;
}
else{
    return false;
}
}

 //Check for errors
 if($error > 0 || is_array($error)){
 die("Sorry an error occured");
}

//Check if file is image
//Only required if image is only whjat we need
//if(!getimagesize($tmp_location)){
//die("Sorry, you can only upload image types");
//}

 if(!imageTypeAllowed($type)){
  die("Sorry, file type is not allowed");
 }

 if(file_exists($final_destination)){
 $final_destination = $upload.'/'.time().$name;
 }

 if(!move_uploaded_file($tmp_location, $final_destination)){
die("Cannot finish upload, something went wrong");
}

?>

<h2>File Successfully uploaded!</h2>
Was it helpful?

Solution

Your server-side code is trying to reference the submitted form data when the page loads, before anything has been submitted. You need to either separate the form handler to a different page or check if the form data exists before referencing it:

if (isset($_FILES['file_upload'])) {
    // your form-handling code
}

OTHER TIPS

You have to wrap your code that is handling posted file with following check:

if ( $_REQUEST['METHOD'] == 'POST' && isset($_FILES['file_upload']) ) {

    $file = $_FILES['file_upload'];
    $name = $file['name'];
    $type = $file['type'];
    $tmp_location = $file['tmp_name'];
    $upload = 'uploads';
    $final_destination = $upload.'/'.$name;
    $error = $file['error'];
    $max_upload_size = 2097152;
    $size = $file['size'];

    // ...

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top