I\'m pretty new to php and I am trying to figure out how to use sessions to check and see if a user is logged into a website so that they would have authorization to access
<?php
session_start();
if(!isset($_SESSION["login"]) && $SESSION["login"] =="OK")){
header("Location: index.php");
exit;
?>
Any page you want to perform session-checks on needs to start with:
session_start();
From there, you check your session array for a variable indicating they are logged in:
if (!$_SESSION["loggedIn"]) redirect_to_login();
Logging them in is nothing more than setting that value:
$_SESSION["loggedIn"] = true;
In Login.html:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
</head>
<body>
<section class="container">
<div class="login">
<h1>Login</h1>
<form method="post" action="login.php">
<p><input type="text" name="username" value="" placeholder="Username"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
</body>
</html>
In Login.php:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
In Member.php:
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
In MYSQL:
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
In Register.html:
<html>
<head>
<title>Sign-Up</title>
</head>
<body id="body-color">
<div id="Sign-Up">
<fieldset style="width:30%"><legend>Registration Form</legend>
<table border="0">
<form method="POST" action="register.php">
<tr>
<td>UserName</td><td> <input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td><td> <input type="password" name="password"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</form>
</table>
</fieldset>
</div>
</body>
</html>
In Register.php:
<?php
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_USER','');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$userName = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO members (username,password) VALUES ('$userName','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
else
{
echo "Unknown Error!"
}
else if (isset($_GET['actie']) && $_GET['actie']== "aanmelden"){
$username= $_POST['username'];
$password= md5($_POST['password']);
$query = "SELECT password FROM tbl WHERE username = '$username'";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
if($password == $row['password']){
session_start();
$_SESSION['logged in'] = true;
echo "Logged in";
}
}
See this script for register. Simple and very easy to understand.
<?php
define('DB_HOST', 'Your Host[Could be localhost or also a website]');
define('DB_NAME', 'databasename');
define('DB_USERNAME', 'Username[In many cases root but some sites offer MySql Page where the username might be different]');
define('DB_PASSWORD', 'whatever you keep[if username is root then 99% password is blank]');
$link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
if (!$link) {
die('Could not connect line 9');
}
$DB_SELECT = mysql_select_db(DB_NAME, $link);
if (!$DB_SELECT) {
die('Could not connect line 15');
}
$valueone = $_POST['name'];
$valuetwo = $_POST['last_name'];
$valuethree = $_POST['email'];
$valuefour = $_POST['password'];
$valuefive = $_POST['age'];
$sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";
if (!mysql_query($sqlone)) {
die('Could not connect name line 33');
}
mysql_close();
?>
Make Sure you make all the Database stuff using phpMyAdmin. Its a very easy tool to work with. You can find it here: http://www.phpmyadmin.net/home_page/index.php
Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.
If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.
I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.
The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].
Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.