0

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>
Samuel Sam
  • 47
  • 7
  • 1
    The code `if($_POST['avatar'] == "")` has the error. The `avatar` field belongs to the `$_FILES` array, not to the `$_POST` array. – shahsani Oct 15 '17 at 18:16
  • Would need his form html to know for sure. Please Sam, add that. But its a pretty spot on stab. – IncredibleHat Oct 15 '17 at 18:18
  • @Randall sorry for the late reply I am having some internet issues. thanks, I have now added the whole code. – Samuel Sam Oct 15 '17 at 18:43

1 Answers1

1

You have referenced the avatar field once as a member of $_POST array, then as member of $_FILES array.

Simply change the if condition with the following to remove the error and also implement the logic you want to perform.

if($_FILES['avatar']['name'] == ""){
     $error[] = "Please Select a Picture!";
}
shahsani
  • 687
  • 7
  • 16
  • You can't say this if you don't know his HTML code, what makes you sure that there is no text input with the name avatar? – Spoody Oct 15 '17 at 18:19
  • 1
    See the message which goes to `$error[]` array. It says, "Please select a Picture" which obviously means the user is trying to check for an uploaded picture - Not a text input with naem avatar – shahsani Oct 15 '17 at 18:22
  • 1
    An educated guess is perfectly fine, when it turns out to be right. So this answer is well and fine acceptable. – IncredibleHat Oct 15 '17 at 18:50
  • @shahsani thanks for your help but I still get the undefined index avatar.. which is coming from the first line with avatar. – Samuel Sam Oct 15 '17 at 18:52
  • Have you put `enctype="multipart/form-data"` in your FORM tag? – shahsani Oct 15 '17 at 18:59
  • @shahsani yes I done that already... now the error only shows when I use edge browser but it works fine with chrome and firefox – Samuel Sam Oct 15 '17 at 19:29