12 PHP 101 Screencast - Sessions and Login

In this screencast I take you throught the basics of using sessions in the context of a login script. Here is the code that I use.

index.php


<?php

	session_start();

	@$login = $_GET['login'];

	if ($login != 'true') {
?>

<!DOCTYPE html>
<html>
	<head>
		<title>Please Login</title>
	</head>
	<body>
		<form method="POST" action="./index.php?login=true">
			<input type="text" name="username">
			<input type="password" name="password">
			<button type="submit">Login</button>
		</form>
	</body>
</html>

<?php
} else {

	@$username = $_POST['username'];
	@$password = $_POST['password'];

	$username = stripslashes($username);
	$password = stripslashes($password);
	$username = mysql_real_escape_string($username);
	$password = mysql_real_escape_string($password);

	$dbhost = 'localhost';
	$dbuser = 'root';
	$dbpass = 'password';
	$dbtable = 'screencast';

	$con = mysql_connect($dbhost,$dbuser,$dbpass);

	if(!$con) {
		die('Could not connect to the DB');
	}
	mysql_select_db($dbtable);

	$sql = "SELECT* FROM users WHERE userName='$username' and password='$password'";
	$result = mysql_query($sql);

	$count = mysql_num_rows($result);

	if($count == 1) {
		if ($obj = @mysql_fetch_object($result)) {
			$_SESSION["userID"] = $obj->id;
			$_SESSION["firstName"] = $obj->firstName;
			$_SESSION["lastName"] = $obj->lastName;
			$_SESSION["emailAddress"] = $obj->emailAddress;

			header("location:./home.php");
		}
	}

}
?>
	

home.php


<?php

require('./session.inc');

if (!$_SESSION["userID"]) {
	header('Location:./index.php');
}

?>

<h1>Hello world</h1>

<a href="./logout.php">Logout here</a>

session.inc


<?php

session_start();

$user_id = $_SESSION["userID"];
$userFirstName = $_SESSION["firstName"];
$userLastName = $_SESSION["lastName"];
$userEmail = $_SESSION["emailAddress"];

?>

logout.php


<?php

session_start();
session_unset();

session_destroy();

header('Location:./index.php');

?>

comments powered by Disqus