1

i trying to create a little project to allow only registered users to login to another page in site , i have 3 PHP page :

Register page login page home page

Register PHP page

<?php
    if(isset($_POST['reg'])){
        $name = $_POST['name'];
        $age = $_POST['age'];
        $address = $_POST['address'];
        $password = md5($_POST['password']);
        
        $con = new PDO("mysql:host=localhost;dbname=newschool","admin","admin");
        $affected = $con->exec("insert into users (name,age,address,password) values('$name',$age,'$address','$password') ");
        if($affected > 0){
            echo "Your data has been added successfully";
        }
    }
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <form action="#" method="post">
            <div class="form-group">
                <label for="name">Username:</label>
                <input type="text" id="name" name="name" class="form-control">
            </div>
            <div class="form-group">
                <label for="age">Age:</label>
                <input type="number" id="age" name="age" class="form-control">
            </div>
            <div class="form-group">
                <label for="address">Address:</label>
                <textarea id="address" name="address" class="form-control"></textarea>
            </div>
            <div class="form-group">
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" class="form-control">
            </div>
            <button name="reg" class="btn btn-primary btn-block">Register</button>
        </form>
    </div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

and login page :

<?php
session_start();
if(isset($_POST['b_login'])){
    $username =$_POST['username'];
    $password =$_POST['password'];
    try{
        $db = new PDO('mysql:host=localhost;dbname=newschool','admin','admin');
       
        $stm = $db->prepare(" select * from users where name= ? and password = ? ");
        $stm->execute([$username,$password]);
        
        if(empty($_SESSION['userinfo']))
    {
        header("Location:Login.php");
    }
    else
    {

        header("Location:home.php");
    }
    }catch (PDOException $ex){

    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">

    <form action="#" method="post">
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username" name="username" class="form-control">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" id="password" name="password" class="form-control">
        </div>
        <button name="b_login" class="btn btn-primary">Login</button>
    </form>
</div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>

i store data in "users" table within MySQL database by name "newschool"

enter image description here

i can register user in database and i can retrieve data by code :

<?php
    try{
        $con = new PDO("mysql:host=localhost;dbname=newschool","admin","admin");
        $users =  $con->query("select * from users");
    }catch(PDOException $e){
        echo "try again";
    }
?>

the problem is when i enter username and password in login page it to forward user to home page !!

Please note that I'm completely new to PHP so if possible a little explanation.

MohamedSalem
  • 37
  • 1
  • 8
  • "when i enter username and password in login page it to forward user to home page" And how exactly is that a problem? What do you want it to do instead of that? – Patrick Q Jan 23 '19 at 14:48
  • [Little Bobby](http://bobby-tables.com/) says [you may be at risk for SQL Injection Attacks](https://stackoverflow.com/q/60174/). Learn about [Prepared Statements](https://en.wikipedia.org/wiki/Prepared_statement) with [parameterized queries](https://stackoverflow.com/a/4712113/5827005). – GrumpyCrouton Jan 23 '19 at 14:55
  • Hello ,the problem when user enter username and password it not forward user to mention page (home) page ? – MohamedSalem Feb 03 '19 at 19:58

3 Answers3

2

It's a late response but for future devs, if you happen to encounter this problem which I really think you won't, the answer is simple and it can be found in Step 5 but looking at your code and screenshots you seem to have not understood how Login Systems work in PHP so I laid out this Guide and I highly recommend that you read it all first before proceeding.

  1. Login Systems work by first checking if the user input matches to something in the database like usernames, names, or id's.

    $stmt = $con->prepare('SELECT * FROM users WHERE name = ?');

  2. Then bind from your prepared statement and make sure to store the results.

$stmt->bind_param('s', $_POST['name']);
$stmt->execute();

// Store the result so we can check it later
$row = $stmt->fetch();
  1. And then check if the username really exist, if it does then perform the password check but if it does not exist, redirect to the login page
// Checks if result exists
if($row){

  // use the 'password verify' only if you encrypt your password in your database if not just do $_POST['password'] == $password (not recommended)
  if(password_verify($_POST['password'], $password)){
    // no need to include the $_POST['password'] in your prepared statement since you will not be executing a SQL command to check for a match of passwords
  } else {
    // redirect if password is not a match to the ones in the database
    header("Location: login.php?error=IncorrectPassword");
  }

} else {
  // redirects to login page 
  header("Location: login.php?error=UsernameNotFound");
}
  1. After the password check, you need to create a session, this is how PHP remembers the user across all of the pages
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $row['name'];
$_SESSION['username'] = $row['username'];

// Then redirect to your homepage
header("Location: index.php");
  1. How to allow only registered users into the index.php? just add this line of code
// checks for session when you enter index.php
if(!isset($_SESSION['username']) || $_SESSION['loggedin'] !== TRUE){
  // redirects you if sessions are not present
  header("Location: login.php");
}

and finally, never forget to add session_start(); to the beginning of all your pages or the sessions won't work.

or check out this code in Github it will make your life easier.

helpmeplease
  • 71
  • 10
0
if(empty($_SESSION['userInfo']))
{
    header("Location: login.php");
}

you can put check something like this on every page

Saurabh Sharma
  • 430
  • 2
  • 11
  • ok i modify login page . but when enter username and password it stuck in login page without forward to home page ? – MohamedSalem Feb 03 '19 at 20:39
0

you have to set cookie variable or session variable when the details are matched with the database and You have check every time on the top of the page that there is value in the variable if there is a value in the variable then the user can go to home page otherwise user is directed on Login Page. Paste code on every page (on the top of the page)

     if(empty($_SESSION['userinfo'])
         {
          header("Location:Login.php");
         }
else
{

header("Location:home.php");
}

in the login page after statement returns true or make the row count

 .......
    $stmt->execute()
    if($query->rowCount() > 0) {
      $_SESSION['username'] = $user;
      header('location:home.php');
    } else {
      header('location:login.php');
    }

.......

use this in your code i am sure that this will help you.

Parjapati
  • 43
  • 5
  • hello Parjapati i modified login page "as above" and add code: if(empty($_SESSION['userinfo'])) { header("Location:Login.php"); } else { header("Location:home.php"); } but when enter username and password it stuck in login page without forward to home page ? – MohamedSalem Feb 03 '19 at 20:22
  • when u check the login details in the login page .. after executing the sql statement . if the statement returns true just save some info in session variable and then redirect it to the "home page " – Parjapati Feb 04 '19 at 16:49
  • sure... when u search for the details in the database at the time of login and when the details are details are verified. just save username or other info in the session variable(for security purpose) and use it to check it on every page . if the user logouts just clear the information in session variable . once when the information in the session variable is deleted just navigate the user on the login page. if there is value in the session variable then throw the user on login page . – Parjapati Feb 05 '19 at 15:12
  • hello,i am not sure i understand above ,please can give more explanation as i am totally new to PHP .thanks for your effort – MohamedSalem Feb 08 '19 at 13:15