I have this code to upload avatar.. It works fine but I get undefined index avatar, if I submit the form with empty avatar. The first code is php code then the Html code follows and the last code is the fileinput code. Thanks for you help pals.
if(isset($_POST['submit'])){
$adminID = $_SESSION['adminID'];
if($_POST['avatar'] == ""){
$error[] = "Please Select a Picture!";
}
$type = explode('.', $_FILES['avatar']['name']);
$type = $type[count($type)-1];
$url = 'assets/images/users/'.$_SESSION['username'].'.'.$type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png', 'JPG', 'GIF', 'JPEG', 'PNG'))) {
if(is_uploaded_file($_FILES['avatar']['tmp_name'])) {
if(move_uploaded_file($_FILES['avatar']['tmp_name'], $url)) {
try { //insert into database with a prepared statement
$stmt = $db->prepare("UPDATE admin SET avatar = '$url' WHERE adminID = $adminID");
$stmt->execute(array(
$adminID
));
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
exit;
}
//else catch the exception and show the error.
catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
}
}
?>
Below is the HTML CODE for the file input, where user will use to select avatar
<div class="col-sm-4 text-center">
<?php
if(isset($error)){
foreach($error as $error){
echo '<p class="btn btn-warning">'.$error.'</p>';
}
}
?>
<input type="file" id="avatar" name="avatar" class="file" data-preview-file-type="any" />
</div>
<button type="submit" id="submit" name="submit" class="btn btn-success pull-right">Save <span class="fa fa-floppy-o fa-right"></span></button>
Here is my fileinput plugin initialization code
<script>
var btnCust = '<button type="button" class="btn btn-secondary" title="Add picture tags" ' +
'onclick="alert(\'Call your custom code here.\')">' +
'<i class="glyphicon glyphicon-tag"></i>' +
'</button>';
$("#avatar").fileinput({
overwriteInitial: true,
maxFileSize: 1500,
showClose: false,
showCaption: false,
showBrowse: false,
browseOnZoneClick: true,
removeLabel: '',
removeIcon: '<i class="fa fa-trash-o"></i>',
removeTitle: 'Cancel or Delete Selection',
elErrorContainer: '#kv-avatar-errors-2',
msgErrorClass: 'alert alert-block alert-danger',
defaultPreviewContent: '<img src="" alt=""><h6 class="text-muted">Click to select</h6>',
layoutTemplates: {main2: '{preview} ' + btnCust + ' {remove} {browse}'},
allowedFileExtensions: ["jpg", "png", "gif"]
});
</script>