0

Hello guy's have read couple of post and search google for answer but not luck.

Basically everything is going fine at the moment with my project. I wanted to display firstname, lastname and avatar for logged in user. here is the what am trying to archive without, http://prntscr.com/cs4xhx is in html at present.

here is what have added already in my header.php

                               <?php if(isset($_SESSION['user_type'])){ ?>
                                <a href class="dropdown-toggle" data-toggle="dropdown">
                                    <img src="<?php echo $_SESSION['avatar']; ?>" alt="" class="img-circle size-30x30">
                                    <span><?php echo $_SESSION['firstname'];?> <i class="fa fa-angle-down"></i></span>
                                </a>
                                 <?php //} ?>

And here is what i have in my profile.php

    <?php
    //error_reporting(E_ALL); ini_set('display_errors', 1);

    session_start();

    if(!isset($_SESSION['user_type'])){
      header('Location: index.php');
    }

    // include file
    require_once('include/connection.php');

    // page title
    $title = "Welcome to your Profile"; 

    // define user session
    $userId = $_SESSION['user_id'];
    $userName = $_SESSION['user_name'];
    $firstname = $_SESSION['firstname'];
    $lastname = $_SESSION['lastname'];


      //include header layout
        require_once('include/header.php');
      ?>
      <?php
          if($_SESSION['user_type'] == 'admin' || $_SESSION['user_type'] == 'leader'){

                // include admin header layout
              require_once('include/admin-header.php');

              }elseif($_SESSION['user_type'] == 'member'){

               // include  member header layout
              include_once('include/member-header.php');

              }else{    

                session_destroy();
                header('Location: index.php');
              }
    ?>
    <!--  check if user id is found, if not throw error ---->
      <?php 
                    $firstname = trim($_POST['firstname']);
                    $lastname = trim($_POST['lastname']);
                    $email = trim($_POST['email']);
                    $user_name = trim($_POST['user_name']);
                    $profession = trim($_POST['profession']);
                    $phone = trim($_POST['phone']);
                    $address = trim($_POST['address']);
                    $bio = trim($_POST['bio']);  
                    $dob = trim($_POST['dob']);
                    $gender = trim($_POST['gender']);
                    $country = trim($_POST['country']);

    $stmt = $con->prepare("SELECT firstname, lastname, user_name, avatar, profession, email, dob, gender, country, phone, bio, address, created_at FROM user WHERE id = ?");
    $stmt->bind_param('s', $userId);
    $stmt->execute();
    $stmt->store_result();  
    if($stmt->num_rows == 0) {  
        echo 'No Data Found for this user';
    }else {
        $stmt->bind_result($firstname, $lastname, $user_name, $avatar, $profession, $email, $dob, $gender, $country, $phone, $bio, $address, $created_at);
        $stmt->fetch();

      //echo $stmt->num_rows


            //          $getUserQuery = "select * from user where id = $userId";
            //          $resultData =   mysqli_query($con, $getUserQuery);
            //                      if(!mysqli_num_rows($resultData)){
            //                          echo 'No Data Found for this user';
            //                      }else{
            //                          $row = mysqli_fetch_array($resultData);
              ?>

          <!-- self post back url  -->
          <?php
              $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
          ?>

          <table>

                <tr>
                  <td>
                        <center>
                              <img src="userfiles/avatars/<?php echo $avatar ;?>" width="150" height="150">
                          </center>

                  </td>
                </tr>
                 <tr>
                   <td><label><strong>First Name</strong></label></td>
                   <td></td>
                    <td><label><?php echo $firstname; ?> </td>
                </tr>
                  <tr>
                   <td><label><strong>Last Name</strong></label></td>
                   <td></td>
                    <td><label><?php echo $lastname;?> </td>
                </tr>
           <tr>
                   <td><label><strong>User Name</strong></label></td>
                   <td></td>
                    <td><label><?php echo $user_name;?> </td>
                </tr>
               <tr>
                   <td><label><strong>Profession</strong></label></td>
                   <td></td>
                    <td><label><?php echo $profession;?> </td>
                </tr>
             <tr>
                 <tr>
                   <td><label><strong>Phone</strong></label></td>
                   <td></td>
                    <td><label><?php echo $phone;?> </td>
                </tr>
             <tr>
                   <td><label><strong>Gender</strong></label></td>
                   <td></td>
                    <td><label><?php echo $gender;?> </td>
                </tr>
                <tr>
                   <td><label><strong>Date Of Birth</strong></label></td>
                   <td></td>
                    <td><label><?php echo $dob;?> </td>
                </tr>
                <tr>
                   <td><label><strong>Email</strong></label></td>
                   <td></td>
                    <td><label><?php echo $email;?> </td>
                </tr>
                <tr>
                   <td><label><strong>Country</strong></label></td>
                   <td></td>
                    <td><label><?php echo $country;?> </td>
                </tr>
              <tr>
                   <td><label><strong>Address</strong></label></td>
                   <td></td>
                    <td><label><?php echo $address;?> </td>
                </tr>
                <tr>
                   <td><label><strong>Biography</strong></label></td>
                   <td></td>
                    <td><label><?php echo $bio;?> </td>
                </tr>
                <tr>
                   <td><label><strong>Join Date</strong></label></td>
                   <td></td>
                    <td><label><?php echo $created_at;?> </td>
                </tr>

          </table>

          <?php 

             }  

          $mysqli->close(); 
          ?>

    <?php 

    // include footer layout
    require_once('include/footer.php');
    ?>

funny enough in the header.php when replace the <?php echo $_SESSION['firstname'];?> with <?php echo $_SESSION['user_name'];?>. it works but when i try to display name and avatar it doesn't, am sure have define session variable or ?.

i hope some can share a light here. Thanks in advance.

UPDATE To identify where and how i set my session header.php

            <script type="text/javascript" src="include/plugins/ckeditor/ckeditor.js"></script>     
            <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> 
            <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>            
        <body>

        <?php if(isset($_SESSION['user_type'])){ ?>
        <div class="logout-link">   
            <p><?php echo $_SESSION['firstname'];?></p>
            <img src="userfiles/avatars/<?php echo $_SESSION['avatar'] ;?>">
          <p><a href="include/logout.php">Logout</a></p>    
        </div>
        <?php } ?>

        <?php if(isset($_SESSION['main_notice'])) { ?>      
            <div class="main-notice">
              <p>
                      <?php
                      echo $_SESSION['main_notice']; 
                      unset($_SESSION['main_notice']);
                      ?>
              </p>
            </div>  
        <?php  }    ?>      

      <ul class="menu">
          <li><a href="admin-dashboard-home.php">Home</a></li>
          <li><a href="profile.php">Profile</a></li>
          <li><a href="edit-profile.php">Edit Profile</a></li>
          <li><a href="admin-post-task.php">Post Task</a></li>
        <li><a href='user-profile.php'>Users Profile</a></li>
    <!--            <li><a href="reset.php">Reset Password</a></li> -->

          </ul>

And here is my index.php

       session_start();

    //error_reporting(E_ALL); ini_set('display_errors', 1);

    // check if user already login
    if(isset($_SESSION['user_type']) && isset($_SESSION['user_id']))
    {
      header('Location: profile.php');
    }

    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    // include database connection
    require_once('include/connection.php');

    if(isset($_POST['submit'])){

    //             // trim form field  
                $user_name = trim($_POST['user_name']);
                $password = $_POST['password'];
              //  $email = trim($_POST['email'], ENT_QUOTES, 'UTF-8');


     // processing remember me option and setting cookie with long expiry date
    //  if (isset($_POST['remember'])) {    
    //      session_set_cookie_params('604800'); //one week (value in seconds)
    //      session_regenerate_id(true);
    //  }


              // form input validation
                if (empty($user_name)){     
                    $error[] = 'Field empty, please enter your username';        
                  }

              // password validation
               if (empty($password)){     
                    $error[] = 'Field empty, please create a password';        
                  }


         //if no errors have been created carry on
           if(!isset($error)){


          //$loginQuery = "select * from user where user_name = '$name' AND password = '$password' AND user_type = '$user_type'";
    //          $loginQuery = "select * from user where user_name = '$user_name' OR email = '$email'";  

    $stmt = $con->prepare("SELECT id, user_name, firstname, lastname, avatar, password, user_type FROM user WHERE user_name = ? ");
    $stmt->bind_param('s', $user_name);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows){
        // username exists
        $stmt->bind_result($id, $username, $firstname, $lastname, $avatar, $dbPassword, $userType);
        $stmt->fetch();
        if (password_verify($password, $dbPassword)) {

            $_SESSION['user_id'] = $id;
            $_SESSION['user_name'] = strtoupper($username);
            $_SESSION["firstname"] = strtoupper($firstname);
            $_SESSION["avatar"] = strtoupper($avatar);
            $_SESSION["lastname"] = strtoupper($lastname);
            $user_type = strtolower($userType);
            if(strtolower($user_type) == 'member'){
                $_SESSION['user_type'] = 'member';  
                //header('Location: member-dashboard-home.php');
                header('Location: profile.php');
                exit();
            }elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
                $_SESSION['user_type'] = strtolower($user_type);                                        
                //header('Location: admin-dashboard-home.php');
                header('Location: profile.php');
                exit();
            }
        }else{
                $_SESSION['main_notice'] = "Invalid login details!";
                header('Location: '.$_SERVER['PHP_SELF']);
                exit();
        }
    }else{
        // username doesn't exist
        $_SESSION['main_notice'] = "Invalid username OR password details, please try again!";
        header('Location: '.$_SERVER['PHP_SELF']);
        exit();
    }
      //$mysqli->close(); 

       }
    }
     // page title function
      $title = 'Task Master | The Whittington Center | Log-in Page';

    // include header
    include_once('include/header.php');
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
olaskee
  • 15
  • 5
  • Do `var_dump($_SESSION);` and see what's inside the session array. – Rajdeep Paul Oct 10 '16 at 16:26
  • @RajdeepPaul... thansk for your interest... pls forgive my ignorant... where do i add the dump. – olaskee Oct 10 '16 at 16:28
  • Add it where you're suspecting `$_SESSION['firstname'];` is not giving you the correct response. – Rajdeep Paul Oct 10 '16 at 16:30
  • hi @RajdeepPaul... yeah it does give me some result here: `array(4) { ["user_id"]=> int(127) ["user_name"]=> string(7) "OLASKEE" ["user_type"]=> string(6) "leader" ["main_title"]=> string(15) "Admin Post Task" }` but i have no clue. – olaskee Oct 10 '16 at 16:33
  • *hmm*, so `$_SESSION['firstname'];` is not set. Check where you're setting this value, like `$_SESSION['firstname'] = "SOME_VALUE";` – Rajdeep Paul Oct 10 '16 at 16:53
  • @Rajdeepaul... no i don't think have set the session for the first name like that. so if am calling a user first name from the database how do I define the session. am guessing something like. $_SESSION ['firstname'] = $firstname; – olaskee Oct 10 '16 at 17:01
  • Yes, that's correct. While logging in, after getting the data from the database you need to set the value like this `$_SESSION['firstname'] = $firstname;` – Rajdeep Paul Oct 10 '16 at 17:08
  • OK but I am think do I then still need to the whole query like `$q = "select...."` or I just need to define it below the `if is set submit` like I did for the username in code I posted initially. – olaskee Oct 10 '16 at 17:23
  • It's hard *predict* anything because I see no such code in your question. Please [edit](http://stackoverflow.com/posts/39962571/edit) your question and post the code where you're setting up these session values i.e. when user logs in. – Rajdeep Paul Oct 10 '16 at 17:30
  • please allow me a moment – olaskee Oct 10 '16 at 17:42
  • @RajdeepPaul... sorry for the delay... so in my index.php i have this .`// session start session_start(); // check if user already login if(isset($_SESSION['user_type']) && isset($_SESSION['user_id'])) { header('Location: profile.php'); } // include database connection require_once('include/connection.php'); if(isset($_POST['submit'])){ // Set session variables $_SESSION["firstname"] = $firstname; $_SESSION["lastname"] = $lastname; // trim form field $user_name = trim($_POST['user_name']); $password = $_POST['password'];` but i want to echo the session in header.php – olaskee Oct 10 '16 at 17:59
  • when i var_dump it this is what i get. http://prntscr.com/cs6mfc – olaskee Oct 10 '16 at 18:03
  • Too many unknowns here. From where you're getting this `$firstname`, `$lastname` etc.? I don't see any `SELECT` query. Also, don't dump your code in the comment section, instead [edit the question](http://stackoverflow.com/posts/39962571/edit) and post your code(and add little bit of explanation stating what you're trying to do and what went wrong) – Rajdeep Paul Oct 10 '16 at 18:10
  • sorry mate i will make amend now – olaskee Oct 10 '16 at 18:11
  • @RajdeepPaul... please take a look now. Thanks – olaskee Oct 10 '16 at 18:21
  • Check these two lines in **index.php**, `$_SESSION["firstname"] = $firstname;` and `$_SESSION["lastname"] = $lastname;`, I think these should be `$_SESSION["firstname"] = $_POST['firstname'];` and `$_SESSION["lastname"] = $_POST['lastname'];` **only if** user is sending firstname and lastname with the form, which I suspect a user shouldn't do while logging in everytime. – Rajdeep Paul Oct 10 '16 at 18:40
  • thanks for that... am now on the move and I will use ur suggested code and revert back to you. hopefully u are still to reply back. thanks for the help and time... really appreciate it – olaskee Oct 10 '16 at 18:44
  • hello @RajdeepPaul... so amend the code in index.php like this... http://prntscr.com/cs7jrr and in my header.php http://prntscr.com/cs7lgz notting change this not display user firstname or lastname – olaskee Oct 10 '16 at 19:09
  • I've given an answer below. Hopefully this will resolve your issue. Go through the answer, **especially** the **Note** section at the bottom of the answer. – Rajdeep Paul Oct 10 '16 at 19:32

1 Answers1

0

See the following lines on index.php page,

$_SESSION["firstname"] = $firstname;
$_SESSION["lastname"] = $lastname;

There's nowhere you have declared $firstname and $lastname in your code, you just magically used them. So remove these two lines, they are useless.

Now comes to your issue. Look at the following statement,

$stmt = $con->prepare("SELECT id, user_name, password, user_type FROM user ...

Neither you have selected firstname, lastname in your SELECT query, nor you have bounded appropriate variables in ->bind_result() method. So your code should be like this:

// your code

$stmt = $con->prepare("SELECT id, user_name, firstname, lastname, password, user_type FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
    // username exists
    $stmt->bind_result($id, $username, $firstname, $lastname, $dbPassword, $userType);
    $stmt->fetch();
    if (password_verify($password, $dbPassword)) {

        $_SESSION['user_id'] = $id;
        $_SESSION['user_name'] = strtoupper($username);
        $_SESSION["firstname"] = $firstname;
        $_SESSION["lastname"] = $lastname;
        $user_type = strtolower($userType);
        if(strtolower($user_type) == 'member'){
            $_SESSION['user_type'] = 'member';  
            //header('Location: member-dashboard-home.php');
            header('Location: profile.php');
            exit();
        }elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
            $_SESSION['user_type'] = strtolower($user_type);                                        
            //header('Location: admin-dashboard-home.php');
            header('Location: profile.php');
            exit();
        }
    }else{
            $_SESSION['main_notice'] = "Invalid login details!";
            header('Location: '.$_SERVER['PHP_SELF']);
            exit();
    }
}else{
    // username doesn't exist
    $_SESSION['main_notice'] = "Invalid username OR password details, please try again!";
    header('Location: '.$_SERVER['PHP_SELF']);
    exit();
}

// your code

Note: To debug these issues, always add these two error reporting lines at the very top of your PHP scripts.

ini_set('display_errors', 1);
error_reporting(E_ALL);
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • thanks for the anwser, so have amend the code, but am getting error. `Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/index.php:1) in /home/index.php on line 7 Warning: Cannot modify header information - headers already sent by (output started at /home/index.php:1) in /home/index.php on line 11` – olaskee Oct 10 '16 at 20:01
  • @olaskee You need to put `session_start();` at the very top of your PHP script, right after opening ` – Rajdeep Paul Oct 10 '16 at 20:06
  • Have manage to sort out the error... but now am not getting redirection after login, is returning a blank empty field – olaskee Oct 10 '16 at 20:20
  • @olaskee Add `exit();` after `header('Location: profile.php');`. I've updated my answer. Also, do `var_dump($_SESSION);` to see the array content. Moreover, have you used the code snippet correctly? See where I've placed these statements `$_SESSION["firstname"] = $firstname;` and `$_SESSION["lastname"] = $lastname;` in my code snippet. – Rajdeep Paul Oct 10 '16 at 20:28
  • Wow... finally work perfectly now... few i most thank so much for your patient and effort, you are good. – olaskee Oct 10 '16 at 20:40
  • Hello Raj... please can take a look at my updated code... have added a data `$avatar` to display user image. The part is correct.. But for some reason that am not seeing the pics not displaying. – olaskee Oct 11 '16 at 11:06
  • **here** http://prntscr.com/csgf88 the large profile image display, but in my project i want to display just login user full name and mini avatar pic at the top, everything else from your help yesterday, but the pics not. – olaskee Oct 11 '16 at 11:07
  • your help will be much appreciated – olaskee Oct 11 '16 at 11:07
  • @olaskee What does this line `` show you? – Rajdeep Paul Oct 11 '16 at 13:42
  • thanks for geting back to me... is only show broken image path... but after moving to the rest of the project, i later found out the image in database is actually not in the folder. so fix this myself. -:) – olaskee Oct 11 '16 at 13:48
  • @olaskee Okay. ;-) However, please modify the existing question. If your requirement is somewhat different from the existing question, form a separate question and ask. – Rajdeep Paul Oct 11 '16 at 13:53