PHP MySQL login

    Below tutorial will help you to create the MySQL login page.

    1. Creating the config.php file that contains the configuration details of the MySQL database.

    <?php
       define('DB_SERVER', 'localhost:3036');
       define('DB_USERNAME', 'root');
       define('DB_PASSWORD', 'root_password');
       define('DB_DATABASE', 'current_database');
       $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
    ?>

    2. Below are the PHP and HTML code for the login page.

    <?php
       include("config.php");
       session_start();
       if($_SERVER["REQUEST_METHOD"] == "POST") {
          // username and password are sent from this form 
          $user_name = mysqli_real_escape_string($db,$_POST['username']);
          $password = mysqli_real_escape_string($db,$_POST['password']); 
          $db_sql = "SELECT id FROM admin WHERE username = '$user_name' and passcode = '$password'";
          $result = mysqli_query($db,$db_sql);
          $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
          $active = $row['active'];
          $count = mysqli_num_rows($result);
    if($count == 1) {
             session_register("myusername");
             $_SESSION['login_user'] = $user_name;
             header("location: welcome.php");
          }else {
             $error = "Your Login Name or Password is invalid";
          }
       }
    ?>
    <html>
       <head>
          <title>Login Page</title>
    </head>
    <div align = "center">
    <form action = "" method = "post">
                      <label>UserName  :</label><input type = "text" name = "username" class = "box"/><br /><br />
                      <label>Password  :</label><input type = "password" name = "password" class = "box" /><br/><br />
                      <input type = "submit" value = " Submit "/><br />
                   </form>
    </div>
    </body>
    </html>

    3. Creating a welcome page that will open after successful login.

    <?php
       include('session.php');
    ?>
    <html>
       <head>
          <title>Welcome To The Site</title>
       </head>
       <body>
          <h1>Welcome Here <?php echo $login_session; ?></h1> 
          <h2><a href = "logout.php">Sign Out</a></h2>
       </body>
    </html>
    
    

    4. Creating a session page to verify the session.

    <?php
       include('config.php');
       session_start();
       $user_check = $_SESSION['login_user'];
       $ses_sql = mysqli_query($db,"select username from admin where username = '$user_check' ");
       $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
       $login_session = $row['username'];
       if(!isset($_SESSION['login_user'])){
          header("location:login.php");
          die();
       }
    ?>

    People are also reading: