Display users name when logged in on the page they are visiting

,

Hello guys, I’m quite a beginner in php and I’ve been trying to deal with this for over a week now but I just don’t know what to do to make this work. I created a simple login system on my website (login.php), containing variables username and password. This works pretty fine but I got another page called advisory (advisory.php) and I want the username from login.php to be displayed in the form in advisory.php (instead of the ‘Anonymous’ value that I temporarily put there) when the user is logged in, as well. And I also would like to have the username displayed through all of the pages of the website. Do you please have any advice how to do that? I have been trying to figure this out with echo "Hello {$_SESSION['account']}"; or echo "Welcome " . $_SESSION['account'] . "!"; or $_SESSION['username'] but no success. I actually don’t know how to make this work, since I’ve set $_SESSION['account'] = $row['id']; but for login.php this works: echo 'You're logged in as ' . $row['username']; but I don’t know how to display the username in the advisory.php and in all the pages of the website. Nothing works so far. Thank you all a lot for any kind of advice!

This is my login.php

 <?php
     session_start();
 ?>  
 // html part
 
     <?php
        if(isset($_SESSION['account'])) {
             $conn = mysqli_connect("localhost", "root", "", "eshop-tech");
             $id = $_SESSION['account'];
             $result = mysqli_query($conn, "SELECT * FROM users WHERE id= $id");
             $row = mysqli_fetch_assoc($result);
 
             echo 'You're logged in as ' . $row['username'];
 
             echo '<div class="logout">
                     <h3>Logout</h3>
                     <form action="logout-sql.php" method="post">
                         <input type="submit" name="submit" value="Logout"><br>
                     </form>
                 </div>';
 
             } else {
 
             echo '<span class="login-page">
             <h3>Log In here</h3><br>
                     <form id="inputs-page" action="login-sql.php" method="post">
                     
                         <div class="form-inputs-page">
                             <input type="text" name="username" placeholder="username"><br>
                        
                             <input type="password" name="password" placeholder="password"><br>
                         </div>
 
                         <div class="forget-page">    
                             <a href="forgot.php">Forgot password?</a>
                         </div><br>    
 
                         
                             <input type="submit" id="send-button-page" name="submit" value="Submit"><br>
                         
 
                         <div class="createacc-page">
                             <a href="signup.php">Sign Up</a>
                         </div>    
                             
                     </form>
 
                 </span>'; 
                  }
     ?>

This is login-sql.php

 <?php

 
 $conn = mysqli_connect("localhost", "root", "", "eshop-tech");
 
 $username = $_POST['username'];
 $password = $_POST['password'];
 
 $sql = "SELECT * FROM users WHERE username = ?";
 
 $stmt = mysqli_stmt_init($conn);
 if (mysqli_stmt_prepare($stmt, $sql)) {
     mysqli_stmt_bind_param($stmt, "s", $username);
     mysqli_stmt_execute($stmt);
     $result = mysqli_stmt_get_result($stmt);
 
     if (mysqli_num_rows($result) > 0) {
         while ($row = mysqli_fetch_assoc($result)) {
             if (password_verify($password, $row['password'])) {
                 session_start();
                 $_SESSION['account'] = $row['id'];
                 header('Location: ' . $_SERVER['HTTP_REFERER']);
                 exit();
             } else {
                 header("Location: login.php?error=invalidusernameorpassword");
                 exit();
             }
 
         }
     } else {
         header("Location: login.php?error=invalidusernameorpassword");
         exit();
     } 
 } else {
     header("Location: login.php?error=sql");
     exit();
 }
 
 ?>

This is my form in advisory.php

 <?php
     session_start();
 

     date_default_timezone_set('Europe/Berlin');
 
     include "advisory-sql.php";
 
     include "advisory-comments.php";
 
 
         echo "<form method='POST' action='".setComments($conn)."'>
             <input type='hidden' name='name' value='Anonymous'>
             <input type='hidden' name='date' value='".date('Y-m-d | H:i:s')."'>
             <textarea name='message' cols='30' rows='10'></textarea><br>
             <input type='submit' name='submitComment' value='Submit'><br>
         </form>";
 
         getComments($conn);
 ?>

This is advisory-comments.php

 <?php

 
 function setComments($conn) {
     if (isset($_POST['submitComment'])) { $name = $_POST['name']; 
     $date = $_POST['date'];
     $message = $_POST['message']; 
 
     $sql = "INSERT INTO advisory (name, date, message) VALUES ('$name', '$date', '$message')";
 
     $result = $conn->query($sql); 
 
     }
 }
 
 
 function getComments($conn) {
     $sql = "SELECT * FROM advisory ORDER BY id DESC LIMIT 5";
     $result = $conn->query($sql);
     while ($row = mysqli_fetch_assoc($result)) {
 
         echo "<div class='comment_box'><p>";
             echo $row['name']."<br>";
             echo $row['date']."<br>";
             echo nl2br($row['message']);
         echo"</p></div>";
     }
 }
 
 ?>

In the login form processing code, you would set a session variable with the user’s id (which is what you are doing.) However, the session variable should be named as to what it is, $_SESSION[‘user_id’], or similar. You would then test for that session variable and query on each page request to get any other user data, such as the username or user permissions.

Your form and form processing code should be on the same page. This will result in the simplest and most secure code. What you are doing now with the - header(“Location: login.php?error=invalidusernameorpassword”) opens your site to a phishing attack, where someone can trick your users to enter their username/passwords on the phishing site, then redirect them to your site and make it look like they miss-typed their username/password.

The code for any page should be laid out in this general order -

  1. initialization
  2. post method form processing
  3. get method business logic - get/produce data needed to display the page
  4. html document

The only redirect you should have in this is upon successful completion of the post method form processing code to the exact same url of the current page to cause a get request for that page.

Some other points about the posted code -

  1. don’t copy variables to other variables for nothing. just use the original variables.
  2. use a prepared query when supplying external, unknown, dynamic values to a query when it gets executed.
  3. to get a form to submit to the same page it is on, leave out the entire action=‘…’ attribute.
  4. if you switch to the much simpler and more modern PDO database extension, about half of the database specific statements will go away.
  5. don’t use a loop to fetch data from a query that will at most match one row of data. just directly fetch the row of data.
  6. don’t use $_SERVER[‘HTTP_REFERER’] in your code. it is not secure.
  7. when you have a conditional branch with an exit/die statement in it, you don’t need an else conditional because the exit/die will stop code execution if that conditional branch is true.
  8. you should be using exceptions for database statement errors (this is the default setting in php8+ for both the mysqli and PDO extensions.) you should only catch and handle database exceptions in your code for user recoverable errors, such as when inserting/updating duplicate user submitted data. in all other cases, simply let php catch and handle and database exception, simplifying the code.
  9. a form’s action=‘…’ attribute is a url. you cannot put php code or a php function call as the target of the action attribute. http requests and responses do not work this way. php code is excuted on the web server when the page is requested. html/javascript/css is rendered/executed in the browser.
  10. you would NOT use a hidden field for the name in your comment form. this is not secure as anyone or anything can set the value to anything they want. if you want to allow Anonymous users to post comments, you would handle this in the server-side post method form processing code. if there is a logged in user, you would use the user_id from the session variable. if there is not a logged in user, you would use whatever value you want for the Anonymous user, but you do this in the code that is using the submitted data.
2 Likes

Thank you so much for your advices! Much appreciated! I basically started over with a new form, according to your words. And it works perfectly! Thank you!!!

Is this the code in this topic?
Although it may “work”, it’s honestly a step backward.
There are no prepared statements. You have reverted from proper password hashing to MD5. That’s just from a cursory scan.

1 Like

thank you. Just saw the difference between MD5 and password_hash in my phpmyadmin database. I’m getting back to password_hash now. Thanks

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.