Sign in, login, logout, signup in php and mysql
PHP – MySQL Sign in
dashboard.php
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php session_start(); if (!isset($_SESSION["username"])) { header("Location: index.php"); // Redirect to login page if not logged in exit(); } echo "Welcome, " . $_SESSION["username"] . "!"; ?> <a href="logout.php">Logout</a> |
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <head> <title>Login Page</title> </head> <body> <h2>Login Page</h2> <form method="post" action="login.php"> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="Login"> </form> </body> </html> |
login.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php session_start(); $servername = "localhost"; $username = "root"; $password = ""; $dbname = "xyz"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $enteredUsername = $_POST["username"]; $enteredPassword = $_POST["password"]; // You should properly sanitize and validate user inputs before using them in queries to prevent SQL injection. $sql = "SELECT * FROM users WHERE username = '$enteredUsername' AND password = '$enteredPassword'"; $result = $conn->query($sql); if ($result->num_rows == 1) { // Login successful $_SESSION["username"] = $enteredUsername; header("Location: dashboard.php"); // Redirect to a dashboard or protected page } else { echo "Login failed. Invalid username or password."; } } $conn->close(); ?> |
logout.php
1 2 3 4 5 6 |
<?php session_start(); session_destroy(); header("Location: index.php"); // Redirect to login page after logout ?> |