-2

I've built a simple user register and login system, using PHP and bootstrap. I am a static designer so PHP is very new to me and I'm struggling with the syntax and logic so far, but I am enjoying it. I actually copied the PHP code from somewhere online but modified it to my project.

After a user logs in, he's directed to his profile page, profile.php

Once in profile page, I want it to say Welcome "firstname". At the moment it says Welcome "username". So somewhere in this code, I think the $username variable is being saved in the session.

I've read up how to do this and I think the logic is - the sessions should be created - the credentials should be saved in an array inside the session - you then call the firstname variable thusly:

<?php echo $_SESSION['firstname']; ?>

Here's my login.php code:

<?php include('../header/header.php') ?>
  <div class="container headingsrow">
      <div class="row">
      <div class="col-6 offset-3">
          <h2>Login</h2>
          <p>Already have an account set up? Log in with your details below:</p>
          <form method="post" action="login.php">
          <?php include('errors.php'); ?>
            <div class="form-group">
              <input type="text" name="username" value="<?php echo $username; ?>" class="form-control" id="inputUsername" placeholder="Email address">
            </div>
            <div class="form-group">
              <input type="password" name="password" value="<?php echo $username; ?>" class="form-control" id="inputPassword" placeholder="Password">
            </div>
            <button type="submit" class="btn btn-primary register" name="login_user">Login <i class="fas fa-sign-in-alt"></i></button>
            <a href="#"><p>Forgotten your password? </p></a><br><br>
          </form>
      </div> 


  </div>

here's my header.php code:

<?php
session_start();
 //After Login
 $_SESSION['id'] = 1;


// initializing variables
$firstname          = "";
$lastname           = "";
$username           = "";
$email              = "";
$telnumber          = "";
$addressline1       = "";
$addressline2       = "";
$city               = "";
$postcode           = "";
$errors = array(); 

// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $firstname = mysqli_real_escape_string($db, $_POST['firstname']);
  $lastname = mysqli_real_escape_string($db, $_POST['lastname']);
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $telnumber = mysqli_real_escape_string($db, $_POST['telnumber']);
  $addressline1 = mysqli_real_escape_string($db, $_POST['addressline1']);
  $addressline2 = mysqli_real_escape_string($db, $_POST['addressline2']);
  $city = mysqli_real_escape_string($db, $_POST['city']);
  $postcode = mysqli_real_escape_string($db, $_POST['postcode']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array

  if (empty($firstname)) { array_push($errors, "First Name is required"); }
  if (empty($lastname)) { array_push($errors, "Last Name is required"); }
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($telnumber)) { array_push($errors, "Telephone number is required"); }
  if (empty($addressline1)) { array_push($errors, "Address line 1 is required"); }
  if (empty($addressline2)) { array_push($errors, "Address line 2 is required"); }
  if (empty($city)) { array_push($errors, "City is required"); }
  if (empty($postcode)) { array_push($errors, "Post code is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
  array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO users (firstname, lastname, username, email, telnumber, addressline1, addressline2, city, postcode, password) 
          VALUES('$firstname', '$lastname', '$username', '$email', '$telnumber', '$addressline1', '$addressline2', '$city', '$postcode', '$password')";
    mysqli_query($db, $query);
    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: index.php');
  }
}

// ... 

// LOGIN USER
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
      $_SESSION['username'] = $username;
      //$_SESSION['success'] = "You are now logged in"  ;
      header('location: profile.php');
    }else {
      array_push($errors, "Wrong username/password combination");
    }
  }
}
?>


<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.css">
    <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
    <title>Prospect Job Vacancies</title>
  </head>
  <body>
    <!-- start of Navbar -->
    <div class="container menubg">
      <div class="row">
        <div class="col">
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="http://vacancies.prospect.local/index.php"><img src="../assets/img/prospect_logo.jpg" class="logo"></a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                  <a href="http://vacancies.prospect.local/index.php"><button type="submit" name="home" class="btn btn-primary">Home <i class="fas fa-home"></i></i></button></a>
                  <!-- <a class="nav-link" href="http://vacancies.prospect.local/registration/register.php">Register <span class="sr-only">(current)</span></a> -->
                </li>                
                <li class="nav-item">
                  <?php
                  if(isset($_SESSION['username'])){
                    echo "<a href=\"http://vacancies.prospect.local/registration/profile.php\"><button type=\"submit\" name=\"home\" class=\"btn btn-primary\">My Account <i class=\"far fa-user\"></i></button></a>";
                }else{
                echo "<a href=\"http://vacancies.prospect.local/registration/register.php\"><button type=\"submit\" name=\"home\" class=\"btn btn-primary\">Register <i class=\"fas fa-user-plus\"></i></i></i></button></a>";
                }
                ;?>  

                </li>                
                <li class="nav-item">
                  <?php
                  if(isset($_SESSION['username'])){
                    echo "<a href=\"http://vacancies.prospect.local/logout.php\"><button type=\"submit\" name=\"logout\" class=\"btn btn-primary\">Logout <i class=\"fas fa-sign-in-alt\"></i></button></a>";
                  }else{
                  echo "<a href=\"http://vacancies.prospect.local/registration/login.php\"><button type=\"submit\" name=\"login\" class=\"btn btn-primary\">Login <i class=\"fas fa-sign-in-alt\"></i></button></a>";
                  } 
                  ;?>
                  <!-- <a class="nav-link" href="http://vacancies.prospect.local/registration/register.php">Register <span class="sr-only">(current)</span></a> -->
                </li>

                  <!-- <a class="nav-link" href="http://vacancies.prospect.local/registration/register.php">Register <span class="sr-only">(current)</span></a> -->
              </ul>
              <span class="navbar-text">
                <a href="https://www.prospect.org.uk/"><i class="fas fa-sign-out-alt"></i> Return to main Prospect website</a>
              </span>
            </div>
          </nav>
          <!-- //end of Navbar -->
        </div>
      </div>
    </div>
    <!-- end of top menu div -->

    <div class="container-fluid jobbg">
      <div class="row">
        <div class="col">
            <div class="container title">
              <div class="row">
                <div class="col">
                  <h1 class="jobheading">Job opportunities with Prospect</h1>
                </div>
              </div>
            </div>
        </div>
      </div>
    </div>

So when I change this part in my profile.php code from:

<?php echo $_SESSION['username']; ?>

to

<?php echo $_SESSION['firstname']; ?>

I get this error:

Welcome 
Notice: Undefined index: firstname in 

C:\xampp\htdocs\vacancies\registration\profile.php on line 46
array(2) { ["id"]=> int(1) ["username"]=> string(11) "bum@bum.com" } 

Ultimately I want it to say Welcome "firstname".

  • Can you try doing `var_dump($_SESSION)` to see what's in there? Update by [edit]ing your question and adding the output of the above text. – Praveen Kumar Purushothaman Apr 30 '18 at 14:29
  • You save the username into the session, but never the firstname. Try saving the firstname into the session the same way you're storing the username. – aynber Apr 30 '18 at 14:37
  • Done Praveen - thanks – Tiger Digital Apr 30 '18 at 14:37
  • Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's – RiggsFolly Apr 30 '18 at 14:39
  • You also do not seem to `start_session()` in the script that you want to output the username. You have to start the session in EVERY script – RiggsFolly Apr 30 '18 at 14:41
  • Hi guys as I said, I am not a php coder - I copied and pasted this code and amended it to my html code. Rather than suggesting what to do - can you guys not just show me please? I have no idea what you're all on about. sorry if I'm not sounding positive, but you are dealing with someone that has very limited php knowledge and asking me to put start_session() on every script is alien to me. – Tiger Digital Apr 30 '18 at 14:51
  • @TigerDigital You don't have a `firstname` in your session. – Praveen Kumar Purushothaman Apr 30 '18 at 14:54
  • Thanks Praveen - how do I add a firstname in my session please? – Tiger Digital Apr 30 '18 at 14:58

2 Answers2

0

All that means is $_SESSION['firstname'] is not defined, in which case you forgot to assign a value to $_SESSION['firstname'] upon user login.

in your header.php :

<?php

session_start();

...

// LOGIN USER
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {

      //fetch result into an associative array.
      $user = mysqli_fetch_assoc($results);

      //$_SESSION['firstname'] should go here
      $_SESSION['firstname'] = $user['firstname'];

      $_SESSION['username'] = $user['username'];
      //$_SESSION['success'] = "You are now logged in"  ;
      header('location: profile.php');
    }else {
      array_push($errors, "Wrong username/password combination");
    }
  }
}
xanadev
  • 751
  • 9
  • 26
  • at last - a human has answered me instead of a robot ! THANK YOU! It works perfectly, and not only that , I can understand the logic and theory of your approach. I can't thank you enough xanadev – Tiger Digital May 01 '18 at 07:48
-1

you try add $_SESSION['firstname'] in here

if (count($errors) == 0) {
  $password = md5($password);
  $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
  $results = mysqli_query($db, $query);
  if (mysqli_num_rows($results) == 1) {
    $_SESSION['username'] = $username;
    $_SESSION['firstname'] = "HERE YOUR FIRST NAME";
    // $_SESSION['success'] = "You are now logged in";
    header('location: profile.php');
  } else {
    array_push($errors, "Wrong username/password combination");
  }
}
Kim
  • 4,080
  • 2
  • 30
  • 51
Hưng hoàng
  • 360
  • 2
  • 5
  • 18
  • again - no idea how to add this, clear as mud, sorry. What file do I put this in and where do I put it in that file pls? – Tiger Digital Apr 30 '18 at 15:00