I have a basic login where the code redirects the user to a page (google.com at the moment). How do I make it so that the page it redirects you to is only accessible if the user is logged in (they can't just type the URL and access the page). I understand that you have to use session start but have read around and cannot come up with a solution.
login.php
<?php
error_reporting(E_ALL | E_STRICT);
$servername = "localhost";
$serverUsername = "root";
$serverPassword = "";
// Create connection
$conn = new mysqli($servername, $serverUsername, $serverPassword, "users");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$loginError = "";
if (isset($_POST["submit"])) {
$username = $conn->real_escape_string($_POST["username"]);
$stmt = $conn->prepare("SELECT Password FROM user_logons WHERE Username = ? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->bind_result($password);
$stmt->execute();
$stmt->fetch();
$stmt->close();
if (password_verify($_POST['password'], $password)) {
header("Location: https://google.com/");
}
else {
$loginError = "Invalid username or password!";
}
}
mysqli_close($conn);
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Login Test</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<span class = "error"><?php echo $loginError; ?></span>
</form>
</body>
</html>
login.php
<?php
error_reporting(E_ALL | E_STRICT);
$servername = "localhost";
$serverUsername = "root";
$serverPassword = "";
// Create connection
$conn = new mysqli($servername, $serverUsername, $serverPassword, "users");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$loginError = "";
if (isset($_POST["submit"])) {
$username = $conn->real_escape_string($_POST["username"]);
$stmt = $conn->prepare("SELECT Password FROM user_logons WHERE Username = ? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->bind_result($password);
$stmt->execute();
$stmt->fetch();
$stmt->close();
if (password_verify($_POST['password'], $password)) {
session_start();
$_SESSION["loggedIn"] = "true";
header("Location: redirect.php");
}
else {
$loginError = "Invalid username or password!";
}
}
mysqli_close($conn);
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Login Test</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<span class = "error"><?php echo $loginError; ?></span>
</form>
</body>
</html>
redirect.php
<?php
error_reporting(E_ALL | E_STRICT);
session_start();
if(!empty($_SESSION['loggedIn'])) {
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Welcome User<h1>
</body>
</html>
<?php
}
else {
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h1 align = "center">Unfortunately, you will need to be logged in to view this section!<h1>
<p align = "center">To return to the login page Click Here</p>
</body>
</html>
<?php
}
session_destroy();
?>
Related
my error is in the mysql database it saves the db login instead of the user's input. also, as from the terminal(linux mint) there is a 302(temp redirect) "error" that is make some error in the code...
from the terminal is: [302]: POST /signupp.php
and all the others is [200]: GET /...
which means this is some of the error right?
now for the code itself:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>hello friend</title>
<meta charset="utf-8">
<style>
body {
font: 1em sans-serif;
}
</style>
</head>
<body>
Home
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
<h1>PHP Login System</h1>
<?php
if (isset($_SESSION["userme"])) {
echo "<a href='profile.php'>Profile</a>";
echo "<a href='logout.php'>Log Out</a>";
}
else {
echo "<a href='/signup.php'>Sign Up</a>";
echo " ";
echo "<a href='/login.php'>Log In</a>";
}
?>
</body>
</html>
db.php
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "phpshop";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
signup.php
<?php
include_once 'index.php';
?>
<h2>Sign Up</h2>
<form action="signupp.php" method="post">
<input type="text" name="namee" placeholder="Full name..">
<input type="email" name="emaill" placeholder="email..">
<input type="text" name="userme" placeholder="username..">
<input type="password" name="passme" placeholder="password..">
<button type="submit" name="submit">Sign Up</button>
</form>
signupp.php
<?php
if (isset($_POST["submit"])) {
$name = $_POST["namee"];
$email = $_POST["emaill"];
$username = $_POST["userme"];
$password = $_POST["passme"];
require_once 'db.php';
require_once 'functions.php';
createUser($conn, $name, $email, $username, $password);
}
else {
header("location: signup.php");
}
functions.php
<?php
function createUser($conn, $namee, $emaill, $userme, $passme) {
$sql = "INSERT INTO GuestsLogs (namee, emaill, userme, passme) VALUES (?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "<script>window.location.href='signup.php';</script>";
exit();
}
$hashedPwd = password_hash($passme, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $namee, $emaill, $userme, $hashedPwd);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<script>window.location.href='signup.php';</script>";
exit();
}
function loginUser($conn, $userme, $passme) {
$passHashed = ["passme"];
$checkPwd = password_verify($passme, "passme");
if ($checkPwd === false) {
echo "<script>window.location.href='signup.php';</script>";
exit();
}
else if ($checkPwd === true) {
session_start();
$_SESSION["userme"] = $passme["userme"];
echo "<script>window.location.href='index.php';</script>";
exit();
}
}
login.php
<?php
include_once 'index.php';
?>
<html>
<head>
<body>
<h2>Sign In</h2>
<form action="loginn.php" method="post">
<input type="text" name="userme" placeholder="Username...">
<input type="password" name=passme placeholder="Password...">
<button type="submit" name="submit" value="submit">Log In</button>
</form>
</body>
</head>
</html>
loginn.php
<?php
if (isset($_POST["submit"])) {
$userme = $_POST["userme"];
$passme = $_POST["passme"];
require_once 'db.php';
require_once 'functions.php';
loginUser($conn, $userme, $passme);
}
else {
header("location: index.php");
exit();
}
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("location: index.php");
exit();
and the profile.php is empty because there is no need for it right now.
You have used the same variable names for db login and user submitted data.
Since you required "db.php" after the user submitted $username and $password, but they are using the same variable names ($username / $password), so the data insertion will use the db credentials for data insertion.
Hence, use the following revised files:
signupp.php
<?php
if (isset($_POST["submit"]) ) {
$namee = $_POST["namee"];
$email = $_POST["emaill"];
$userme = $_POST["userme"];
$passme = $_POST["passme"];
require_once 'db.php';
require_once 'functions.php';
createUser($conn, $namee, $email, $userme, $passme);
}
else {
echo "<script>window.location.href='signup.php';</script>";
}
functions.php
<?php
function createUser($conn, $name, $email, $username, $password) {
$sql = "INSERT INTO GuestsLogs (namee, emaill, userme, passme) VALUES (?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
echo "<script>window.location.href='signup.php';</script>";
exit();
}
mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $username, $password);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<script>window.location.href='signup.php';</script>";
exit();
}
signup.php
<?php
include_once 'index.php';
?>
<h2>Sign Up</h2>
<form action="signupp.php" method="post">
<input type="text" name="namee" placeholder="Full name..">
<input type="email" name="emaill" placeholder="email..">
<input type="text" name="userme" placeholder="username..">
<input type="password" name="passme" placeholder="password..">
<button type="submit" name="submit">Sign Up</button>
</form>
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>hi</title>
<meta charset="utf-8">
</head>
<body>
Home
Sign Up
</body>
</html>
I am new to PHP and was following a login_registration script the registration process works fine and the user is added to the database, however, when I try to log in it shows error I checked php.error log on wamp server and it says this,
PHP 1. {main}() C:\wamp64\www\php\login_register_system\login.php:0
Here is my code
connect.inc.php
<?php
//$conn_error = "could not connect";
$mysql_host= "localhost";
$mysql_user = "root";
$mysql_pass ="";
$mysql_db ="a_database";
$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_pass,$mysql_db);
/*if(!mysqli_connect($mysql_host,$mysql_user,$mysql_pass) && !mysqli_select_db($mysql_db)){
die($conn_error);
}
*/
if(!$conn){
die("Connection failed: ". mysqli_connect_error());
}
?>
registration.php
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<title>Registartion</title>
<link rel ="stylesheet"href="style.css"/>
</head>
<body>
<?php
require "connect.inc.php";
if(isset($_REQUEST["username"])){
$username =stripslashes($_REQUEST["username"]);
$username =mysqli_real_escape_string($conn,$username);
$email =stripslashes($_REQUEST["email"]);
$email =mysqli_real_escape_string($conn,$email);
$password =stripslashes($_REQUEST["password"]);
$password =mysqli_real_escape_string($conn,$password);
$trn_date = date("Y-m-d H:i:s");
$query ="INSERT INTO `users2` (username,password,email,trn_date) VALUES('$username','".md5($password)."','$email','$trn_date')";
$result =mysqli_query($conn,$query);
if($result){
echo "<div class='form'>
<h3>You are registered succesfully</h3><br>
Click here to <a href='login.php'>Log in</a>
</div>";
}
}else{
?>
<div class="form">
<h1>Registration</h1>
<form name="registration" action ="registration.php" method="post">
<input type="text" name ="username" placeholder ="Username" required/>
<input type="text" name ="email" placeholder ="Email" required/>
<input type="password" name ="password" placeholder ="password" required/>
<input type="submit" type="submit" value="Register"/>
</form>
</div><!--form-->
<?php } ?>
</body>
</html>
login.php
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<title>Login</title>
<link rel ="stylesheet"href="style.css"/>
</head>
<body>
<?php
//ini_set('display_errors','1');
//error_reporting(E_ALL);
require "connect.inc.php";
session_start();
if(isset($_POST["username"])){
$username = stripslashes($_REQUEST["username"]);
$username = mysqli_real_connect($conn,$username);
$username = mysqli_real_escape_string($conn,$password);
$query ="SELECT * FROM `users` WHERE username ='$username' and password ='".md5($password)."' ";
$result =mysqli_query($conn,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION["username"] = $username;
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect</h3><br>
Click here to <a href='login.php'>Login</a>
</div>";
}
}else{
?>
<div class="form">
<h1>Login </h1>
<form action="login.php" method="post" name="login">
<input type="text" name ="username" placeholder ="Username" required/>
<input type="passowrd" name ="password" placeholder ="password" required/>
<input type="submit" type="submit" value="Login"/>
</form>
</div>
<?php } ?>
</body>
</html>
logout.php
<?php
session_start();
if(session_destroy()){
header("Location: login.php");
}
?>
index.php
<?php
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome home</title>
</head>
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION["username"];?></p>
<p>This is secure area</p>
Logout
</div>
</body>
</html>
Any help will be highly appreciated. Thanks.
Do note this is just for learning the purpose. I know there are flaws but please be easy.
Just change this,
$username = stripslashes($_REQUEST["username"]);
$username = mysqli_real_connect($conn,$username);
$password =stripslashes($_REQUEST["password"]);
$password = mysqli_real_escape_string($conn,$password);
to the following,
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($conn, $username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn, $password);
I hope you have only one user related to the entered credentials in the database. Hope this helps you!
thanks i got it resolved..problem was this line $query ="SELECT * FROM users WHERE username ='$username' and password ='".md5($password)."' "; in login.php..
correct should be this
$query ="SELECT * FROM `users2` WHERE username ='$username' and password ='".md5($password)."' ";
i was checking data in users table whereas i registered in users2 table..as i had many tables that created confusion
I made a registration form. it actually works but it shows the "Failed To Register, Try Again" message.
Here's my code.
HTML and PHP
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="#" method="POST">
<h3>Register</h3>
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" name="btn">
</form>
</body>
</html>
<?php
if (isset($_POST['btn'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
mysql_connect("localhost","root","");
mysql_select_db("login2");
$query = "INSERT INTO users VALUES ('','$username','$password')";
mysql_query($query);
echo "Registered Successfully";
}
else {
echo "Failed To Register, Try Again";
}
?>
You can check the post.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
Also add uname and pass control.
<?php
if (isset($_POST['uname']) && !empty($_POST['uname']) && isset($_POST['pass']) && !empty($_POST['pass'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
............................
}
else {
echo "Failed To Register, Try Again";
}
?>
1.There is a problem with you if statement which shows failed to register on page load
Mysql is deprecated, use mysqli_*.
Here is an updated code
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="#" method="POST">
<h3>Register</h3>
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" name="btn" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['btn'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
mysqli_connect("localhost","root","");
mysqli_select_db("login2");
$query = "INSERT INTO users VALUES ('','$username','$password')";
$results=mysqli_query($query);
if(mysqli_affected_rows($con)>0){ //check if inserted
echo "Registered Successfully";
}
else{
echo "Failed To Register, Try Again";
}
}
?>
Try the below code and check
<?php
if (isset($_POST['btn'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
mysql_connect("localhost","root","");
mysql_select_db("login2");
$query = "INSERT INTO users VALUES ('','$username','$password')";
if(mysql_query($query))
{
echo "Registered Successfully";
}
else
{
echo "Failed To Register, Try Again";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="#" method="POST">
<h3>Register</h3>
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" name="btn">
</form>
</body>
</html>
<?php
if (isset($_POST['btn']))
{
$username = $_POST['uname'];
$password = $_POST['pass'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users(`username`, `password `) VALUES ('$username','$password ')";
$result = $conn->query($sql);
if (!$result)
{
echo("Error description: " . mysqli_error($conn));
}
else
{
echo "successfully inserted";
}
}
?>
I tried to hosting my php, and found error: 404 when start login. What should I do? I've searched various solutions and repeatedly fixed my php code, but it did not work very well. There is a solution that says that the error is caused .htaccess. How to use htaccess? Please help. I'm a beginner. Here i will include my php code.
admin-login.php
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($dbC,$_POST['username']);
$mypassword = mysqli_real_escape_string($dbC,$_POST['password']);
$sql = "SELECT * FROM akun WHERE id = '$myusername' and password = '$mypassword'";
$result = mysqli_query($dbC,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_register("myusername");
$_SESSION['login_user'] = $myusername;
header("location: admin-halomedan.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Halo Medan</title>
<link rel="icon" type="image/png" href="img/icon.png">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper" style="height: 100%; width:100%; background: #FFBD30;">
<div class="boxmenu">
<img src="img/halomedan1.png" style="text-align:center;">
</div>
<div class="header" style="padding-top:100px;">
<form action="" method="POST" style="text-align:center;">
<input type="text" name="username" placeholder="Username" class="login_regis"><br/>
<input type="password" name="password" placeholder="Password" class="login_regis"><br/>
<input type="Submit" name="submit" value="LOGIN" class="tombol_login">
</form>
</div>
</div>
</body>
</html>
config.php
<?php
$dbHost = "mysql.hostinger.in";
$dbUser = "user db";
$dbPass = "my password";
$dbName = "my database";
$dbC = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName)
or die("Error Connecting to MySQL DataBase");
?>
session.php
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($dbC,"SELECT nama from akun where id = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
if(!isset($_SESSION['login_user'])){
header("location:admin-halomedan.php");
}
?>
admin-halomedan.php
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Nyekrip Halaman Khusus</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Selamat Datang : <i><?php echo $_SESSION; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
When I hit my submit button to login nothing happens. I am just getting the same page, and not even an error. The connection to db should be fine. I have been looking at the code for 10 hours now, and I cannot figure out why. Does anybody have an idea?
dbconfic.inc.php:
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "testdb";
// connection:
$mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
// tjek conenction:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
// vi kører utf-8 på connection:
$mysqli->set_charset("utf-8");
?>
index.php:
<?php
include('login.php'); // Include Login Script
if(isset($_SESSION['username']))
{
header('Location: home.php');
}
exit();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" value="Login" />
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>
login.php:
<?php
session_start();
include("dbconfic.inc.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: home.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}
}
}
?>
home.php:
<?php
include("check.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
check.php:
<?php
include('dbconfic.inc.php');
session_start();
$user_check=$_SESSION['username'];
$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['username'];
if(!isset($user_check))
{
header("Location: index.php");
}
?>
logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
The index page seems more or less ok, a minor alteration to the use of isset and the inclusion of the login.php script.
The check.php does an extra db lookup - you should be able just to use the session info to judge whether or not to redirect the user - so rather than echo $login_user in the html use $_SESSION['username']
In the login.php script use prepared statements if possible to help mitigate against sql injection, and if possible avoid hashing passwords with md5!
<?php
$error='';
if( !isset( $_SESSION ) ) session_start();
if( !isset( $_SESSION['username'] ) ) include( login.php' );
else exit( header('Location: home.php') );
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>PHP Login Form with Session</title>
<link rel='stylesheet' href='style.css' type='text/css' />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class='loginBox'>
<h3>Login Form</h3>
<br><br>
<form method='post' action=''>
<label>Username:</label><br>
<input type='text' name='username' placeholder='username' /><br><br>
<label>Password:</label><br>
<input type='password' name='password' placeholder='password' /><br><br>
<input type='submit' name='submit' value='Login' />
</form>
<div class='error'><?php echo $error;?></div>
</div>
</body>
</html>
<?php
/* login.php */
$error = '';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'], $_POST['username'], $_POST['password'] ) ) {
if( empty( $_POST['username'] ) || empty( $_POST['password'] ) ){
$error = 'Both fields are required.';
}else {
/*
Use prepared statements - mitigates agsint sql injection.
Use placeholders in the sql which are used by the `bind_param` statement
*/
$sql='select `uid` from `users` where `u_username`=? and `password`=? limit 1';
$stmt=$db->prepare( $sql );
if( !$stmt ) exit('Failed to prepare sql statement');
/*
md5 is not recommended for password hashing as it is generally considered to be broken
bind the variables to the placeholders & execute the sql
*/
$username=$_POST['username'];
$password=md5( $_POST['password'];
$stmt->bind_param('ss', $username, $password ) );
$res=$stmt->execute();
/* bind the result of the query to a variable */
$stmt->bind_result( $login_user );
while( $stmt->fetch() ){
/* go through recordset ( 1 record ) */
$_SESSION['username'] = $login_user;
}
$stmt->close();
$db->close();
if( isset( $_SESSION['username'] ) ) exit( header( 'location: home.php' ) );
else $error='Incorrect username or password.';
}
}
?>
<?php
/* home.php */
if( !isset( $_SESSION ) ) session_start();
if( !isset( $_SESSION[ 'username' ] ) ) exit( header('Location: index.php') );
#include("check.php"); /* serves no real purpose once session is set */
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $_SESSION['username'];?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
Database:
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "testdb";
// connection:
$mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
// tjek conenction:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
// vi kører utf-8 på connection:
$mysqli->set_charset("utf-8");
?>
Index:
<?php
session_start();
if(isset($_SESSION['username']))
{
header('Location: home.php');
}else{
include('login.php');
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="index.php">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" name="dologin" value="Login" />
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>
?>
Login:
<?php
include("dbconfic.inc.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["dologin"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: index.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}
}
}
?>
HOME:
<?php
include("check.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
Check:
<?php
session_start();
include('dbconfic.inc.php');
$user_check=$_SESSION['username'];
$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['username'];
if(!isset($user_check))
{
header("Location: index.php");
}
?>