Why the variable is showing undefined when using Sessions - php

I have a login system and when the users login, they are sent to a new file called user.php. In the login file, I have this code:
$user = $check->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
and when the user successfully logs in, he is sent to the user.php file and the code in the the file looks like:
<?php
// Start The session
session_start();
// Chaeck if the user is logged in.
if ($_SESSION['logged_in'] = false) {
$_SESSION['message'] = 'You must Login to continue use this section.';
header('location: error.php');
} else {
$username = $_SESSION['username'];
echo $username;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h1>
Welcome, <?php echo $username?>,
</h1>
</body>
</html>
But when the user logs in he gets the undefined index: username. I want to know why if I am using Sessions.

$user = $check->fetch_assoc();
if(!empty($user)) {
$passwordCheck = password_verify($_POST['password'], $user['password'])
if ($passwordCheck) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
}
Here is modified welcome page
<?php
// Start The session
session_start();
// Chaeck if the user is logged in.
if (!isset($_SESSION['logged_in']) && $_SESSION['logged_in']=="") {
$_SESSION['message'] = 'You must Login to continue use this section.';
header('location: error.php');
} else {
$username = $_SESSION['username'];
echo $username;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h1>
Welcome, <?php echo $username?>,
</h1>
</body>
</html>

Please next time try to send a full code so that helping you will become a lot easier. Username is undefined probably because you did not initialize session session_start(); in your authentication script eg login.php that first handle the session. Again u will need to mitigate session fixation attack by generating new session for each login user session_regenerate_id();
$user = $check->fetch_assoc();
if (password_verify($_POST['password'], $user['password'])) {
// initialize session
session_start();
// prevent session fixation attack
session_regenerate_id();
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user['username'];
header('location: user.php');
}
Optionally
At user.php
Remove the way your are performing session check and replace the code below.
you can check if users session is set using this simple script
<?php
// initialize session if session has not be initialize otherwise remove it
session_start();
if(!isset($_SESSION['username']) || (trim($_SESSION['username']) == '')) {
echo "you must login";
exit();
}else{
// login flows
}
?>
Pls send full code if this does not solve your problem

Related

Bowser gets logged in even after logged out on clicking back option

I have built a login page using php and pdo and created and logged in properly but after clicking log out button if I click back again it again goes to my page which appear only if logged in I even used session but it is not running properly even
<?php
include('connect.php');
session_start();
if(isset($_POST['logout'])){
{
unset($_SESSION['logged_in']);
session_destroy();
header("location:index12.php");
}
}
if(isset($_POST['login']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$errflag = false;
if($username == '' and $password == '') {
echo "you must enter username and password";
$errflag = true;
}
if ($errflag == false) {
SignIn($username,$password);
}
}
function SignIn($username,$password){
global $connect;
$search = $connect->prepare("SELECT * FROM users where username =
:username AND password = :password ");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$search->execute();
$count = $search->rowCount();
if($count> 0)
{
$_SESSION['username'] = $_POST['username'];
if(!isset($_SESSION['logged_in']))
header("Location: myfile.php");
}
else{
echo "wron email or password";
}
}
?>
the code of inner page is
<?php
echo "welcome to the website ";
echo "congrats you are logged in ";
?>
<html>
<head>
<title>
welcome here</title>
</head>
<body>
<form method ="POST" action = "login.php">
<button name="logout" style="float:right;">logout</button>
</form>
<h1><center>google is one of the best search engine</center></h1>
</body>
</html>
thankyou I updated the in the above manner but it is not working
Add bit of code session_start(); at the beginning of the page.
<?php
session_start();
if(isset($_POST['logout'])){
{
unset($_SESSION['logged_in']);
session_destroy();
header("location:index12.php");
}
}
?>
Also if you have not start session in connect.php ,you must need to start session by using session_start();
<?php
session_start();
include('connect.php');
I don't know how do you start your session but this a suggestion:
I generally write a new_session() function which looks like the following. I do prefer to set cookie params so we can have some control over it.
function new_session()
{
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], Sessions::SECURED_COOKIES, Sessions::HTTP_ONLY);
session_name('My_Awesome_App');
session_start();
session_regenerate_id();
}
And another one to destroy everything
function destroy_session()
{
session_unset();
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
session_destroy();
}
You can find the documentation about session_get_cookie_params() here
and about session_set_cookie_params() here
Back to your example
Using this new function you should call new_session() on top of your pages and your logout should look like.
new_session();
if (isset($_POST['logout'])) { {
unset($_SESSION['logged_in']);
destroy_session(); // our new function
header("location:index12.php");
}
}

PHP Login and session

Good morning/evening,
I'm stuck and I need some help in PHP.
I am trying to code up an admin dashboard. And I want to check if user is logged in, if not , redirect to the login page.
My index.php is this:
<?php
$pagename ="Index";
#require_once('inc/head.php');
?>
<body>
CONGRATS! Welcome to the Admin dashboard.
</body>
</html>
My login page:
<?php
$pagename = "login";
$adminUser = "admin";
$adminPass = "admin";
#require_once('inc/head.php');
// If POST is submitted and IDs match the ones set
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["username"] == $adminUser && $_POST["password"] == $adminPass)
{
session_start();
$_SESSION["username"] = $adminUser;
$_SESSION["login"] = true;
echo '<script>alert("Congrats, you logged in");
window.location = "index.php"; </script>';
/* I skip the line underneath because for unknown reasons my code
Doesn't fully run through. So I redirected with the JS above instead.
header("Location: index.php");
exit(); */
}else{
echo '<script>alert("Incorrect username or password!'");</script>';
}
}
?>
<html>
<!-- login page here -->
</html>
And here goes my head.php:
<?php
// If we AREN'T on the login page , check if session exist. If not send to login
if($pagename != "login")
{ if(!$_SESSION['login'])
{
header('location: login.php');
exit();
}
}
?>
There is alot of things wrong with this and I know but as of now I'm trying to fix my login in issue. Whenever I log in I get the JS pop up that says I successfully logged in, but I don't get redirected to the index. I think I do get sent to my index.php ( there's no reason for my JS redirect to NOT function ) but my index sends me right back to login and I don't understand why.
Start Session in head.php page.
head.php
<?php
if($pagename != "login") {
session_start();
if(!$_SESSION['login']) {
header('location: login.php');
exit();
}
}
?>

STARTING a LOGIN SESSION in PHP

I have created a login script and it works fine, however, I would like to implement sessions.. I am currently having some trouble with it because my session script is only partially executed. Below is my login script and the test page I'd like it to redirect to, IF the user is logged in.. I want it to display the test page, if not, then I want it to redirect back to the login page (or in this case, the index.php file) and ask the user to login... see code below:
loginconfig.php:
<?php
// Create a connection
include("dbconfig.php");
if (isset($_POST['submit'])) {
if (empty($_POST['username']) or empty($_POST['password'])) {
header("location:index.php?msg0=Please complete the required fields.");
}
elseif (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysqli_query($conn, "SELECT * FROM logininformation WHERE username = '$username' and password = '$password'") or die(mysqli_error($conn));
$login = ($sql) ? mysqli_fetch_assoc($sql) : false;
if (($login) == 0) {
header("location:index.php?msg1=Invalid username or password, please try again.");
}
elseif (($login) > 0) {
session_start();
$_SESSION['login'] = $_POST['username'];
//header("location:index.php?bid=$username&msg2=You are unable to log in at this time. Website is under construction.");
header("location:test.php?bid=$sessionwork");
}
}
}
?>
test.php:
<?php
session_start();
include("dbconfig.php");
$username = $_GET['bid'];
var_dump($_SESSION['login'];
// If user is logged in:
if(!empty($_SESSION['login'])){
echo "Welcome $username";
}
// If user is not logged in:
elseif(!isset($_SESSION['login'])){
header("location:index.php?msg4=You need to be logged in!");
}
?>
<html>
<head>
<title> user page </title>
</head>
<body>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" value="logout">
</form>
</body>
</html>
logout.php
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
Now if you look at the test.php file.. I have sort of told it to check if a user is logged in. But unfortunately, the script only manages to execute the script where it says if the user is not logged in.. redirect to index.php... even if the user enters the correct login credentials and actually logs in. What could be the issue?
Any help will be much appreciated.
It should be like this in test.php:
if(isset($_SESSION['login'])){
echo "Welcome $_SESSION['login']";
}
else{
header("location:index.php?msg4=You need to be logged in!");
}
The same error is repeated in loginconfig.php.
Initially, I did not have a logout.php file.. therefore I was making the mistake of not destroying my session. The change I had to make to my initial scripting was to create a logout.php file. But when I did, the problem was still present.. in order for it to work.. I made the following changes to the logout.php file.. see below:
BEFORE:
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
AFTER:
<?php
session_start();
session_destroy();
header("location:index.php");
exit();
?>
Thank you for those who helped, especially #Epodax for the GREAT support.

only show page if session isset and variable ==

i'm trying to add roles for certain pages on a small internal site i am running.
i assign the following sessions when user logs into the site login form;
// Register $username, $role Sessions and redirect
$_SESSION['username']= $username;
$_SESSION['accessLevel'] = $role;
$_SESSION['is_logged_in'] = true;
i then have the following on my logout.php page;
<?php
session_start();
session_destroy();
header("Location: ../login.php");
?>
i want to restrict page based on the users $_SESSION['accessLevel']
for instance only show page if $_SESSION['accessLevel'] == 'admin' else redirect to login page (or error page)
here is what i have on an admin page;
<?php
session_start();
if (!isset($_SESSION['username']) && $_SESSION['accessLevel'] == 'admin'){
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<p>ADMIN AREA!! </p>
<p>username: <?php echo $_SESSION['username'];?></p>
<p>Access: <?php echo $_SESSION['accessLevel'];?></p>
</body>
</html>
<?php
}
else {
header("location:../login.php");
}
?>
now the page redirects to login.php when i login using admin credentials if i remove the check i print_r the sessions are correct;
$_SESSION['accessLevel'] = admin
$_SESSION['username'] = testuser
where am i going wrong?
You want the username to exist, right now you are checking to see if it is not isset(). Update your conditional to:
if(isset($_SESSION['username']) && $_SESSION['accessLevel'] == 'admin') {
// HTML here
} else {
header("location:../login.php");
}
Also, a side note: if you ever have an edge case were you set a username value but not a accessLevel value, you will get a fatal error with this conditional. You should be making sure that the accessLevel is set to be safe:
isset($_SESSION['username'], $_SESSION['accessLevel']) && $_SESSION['accessLevel'] == 'admin'

Does this login system function need to replace any of my current code and where do I place it?

At the moment this is how my login and logoff system works:
When a user logs in, it stores in their details in a $_SESSION in a script known as member.php:
if (isset($_SESSION['teacherid'])) {
$userid = $_SESSION['teacherid'];
}
if (isset($_SESSION['teacherusername'])) {
$username = $_SESSION['teacherusername'];
}
Then in every script it contains the code below where the sessionlife lasts for 12 hours:
<?php
ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_divisor', '1');
ini_set('session.gc_probability', '1');
ini_set('session.cookie_lifetime', '0');
require_once 'init.php';
session_start();
include(member.php)
?>
init.php is this below:
<?php
session_save_path('Session');
?>
Now after 12 hours the next time the user refreshes the page, as the session will be destroyed, it goes to the logoff page:
if ((isset($username)) && (isset($userid))){
session_destroy();
echo "You have been Logged Out | <a href='./home.php'>Home</a>";
}
else {
echo "You are Not Logged In";
}
Obviously if the user clicks on the logout page then it navigates to script above.
But I found out a better way to keep user's logged in and for them to not logout until they log themselves out is with this code below:
if (session_exists) continue();
else if (!session_exists AND cookie_exists AND validate_cookie()) {
login_user_via_cookie();
continue();
else show_login_page();
My question, is first of all where do I place this code, do I replace it with the session_maxlife and all of the ini_set code I set? Do I need to replace any of that code and do I need to change the code I found above to get it working in my script? (My logout page is in a script known as Text4.php)
Thanks
UPDATE:
teacherlogin.php page:
<?php
/*
file: login.php
authorized (logged in) users must be redirected to a secure page (member.php) or (secure.php)
unauthorized (guests) users have to see the login form
*/
#include the class file and start it.
require_once('session.class.php');
$session = new Session();
#check user's access
if($session->get("auth")) header("location:member.php");
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
// connect to the database
include('member.php');
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
// required variables (make them explciit no need for foreach loop)
$teacherusername = (isset($_POST['teacherusername'])) ? $_POST['teacherusername'] : '';
$teacherpassword = (isset($_POST['teacherpassword'])) ? $_POST['teacherpassword'] : '';
$loggedIn = false;
$active = true;
if ((isset($username)) && (isset($userid))){
echo "You are already Logged In: <b>{$_SESSION['teacherforename']} {$_SESSION['teachersurname']}</b> | <a href='./menu.php'>Go to Menu</a> | <a href='./teacherlogout.php'>Logout</a>";
}
else{
if (isset($_POST['submit'])) {
$teacherpassword = md5(md5("g3f".$teacherpassword."rt4"));
// don't use $mysqli->prepare here
$query = "SELECT TeacherId, TeacherForename, TeacherSurname, TeacherUsername, TeacherPassword, Active FROM Teacher WHERE TeacherUsername = ? AND TeacherPassword = ? LIMIT 1";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ss",$teacherusername,$teacherpassword);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbTeacherId, $dbTeacherForename,$dbTeacherSurname,$dbTeacherUsername,$dbTeacherPassword, $dbActive);
while($stmt->fetch()) {
if ($teacherusername == $dbTeacherUsername && $teacherpassword == $dbTeacherPassword) {
if ($dbActive == 0) {
$loggedIn = false;
$active = false;
echo "You Must Activate Your Account from Email to Login";
}else {
$loggedIn = true;
$active = true;
$_SESSION['teacherid'] = $dbTeacherId;
$_SESSION['teacherusername'] = $dbTeacherUsername;
}
}
}
if ($loggedIn == true){
$_SESSION['teacherforename'] = $dbTeacherForename;
$_SESSION['teachersurname'] = $dbTeacherSurname;
header( 'Location: menu.php' ) ;
die();
}
if (!$loggedIn && $active && isset($_POST)) {
echo "<span style='color: red'>The Username or Password that you Entered is not Valid. Try Entering it Again</span>";
}
/* close statement */
$stmt->close();
/* close connection */
$mysqli->close();
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Teacher Login</title>
<link rel="stylesheet" type="text/css" href="TeacherLoginStyle.css">
</head>
<body>
<?php
include('noscript.php');
?>
<h1>TEACHER LOGIN</h1>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" id="teachLoginForm">
<p>Username</p><p><input type="text" name="teacherusername" /></p> <!-- Enter Teacher Username-->
<p>Password</p><p><input type="password" name="teacherpassword" /></p> <!-- Enter Teacher Password-->
<p><input id="loginSubmit" type="submit" value="Login" name="submit" /></p>
</form>
Forgot Password
</body>
<?php
}
?>
</html>
teacherlogout.php page:
<?php
require_once('session.class.php');
$session = new Session();
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Menu</title>
<link rel="stylesheet" type="text/css" href="menu.css">
</head>
<?php
include('member.php');
include('noscript.php');
?>
<body>
<?php
if($session->get("auth")){
session_destroy();
echo "You have been Logged Out | <a href='./home.php'>Home</a>";
}
else {
echo "You are Not Logged In";
}
?>
</body>
</html>
member.php page:
<?php
/*
file: secure.php, profile.php, member.php
authorized (logged in) users => log them out and show goodbye msg or send them to login.php
unauthorized (guests) users => redirect them to login.php
*/
require_once('session.class.php');
$session = new Session();
#if user is not logged in, he will be sent to the login.php page
#note the (!) sign before the $session, it means if the $session->get("auth") == false
if(!$session->get("auth")) header("location:teacherlogin.php");
#if user is not logged in, he will be sent to the login.php page
#note the (!) sign before the $session, it means if the $session->get("auth") == false
if(!$session->get("auth")) header("location:teacherlogin.php");
//need to the code below in order to store details of teacher that is logged in (needed for queries in other pages)
if (isset($_SESSION['teacherforename'])) {
$_SESSION['teacherforename'] = $_SESSION['teacherforename'];
}
if (isset($_SESSION['teachersurname'])) {
$_SESSION['teachersurname'] = $_SESSION['teachersurname'];
}
if (isset($_SESSION['teacherid'])) {
$userid = $_SESSION['teacherid'];
}
if (isset($_SESSION['teacherusername'])) {
$username = $_SESSION['teacherusername'];
}
?>
Here is a Class you can use and edit if you need to:
File session.class.php
<?php
/*
Simple PHP Session Class:
a simple class to help managing the Session function in
php for beginners and it introduces them to OOP where
they can modify it and add new features and extend its
functionality (session in database, track users actions,etc)
*/
#Session settings.
#Session cookie lifetime at the user browser. (seconds)
ini_set('session.cookie_lifetime', '0');
#Read the functions reference below before you change these values.
ini_set('session.gc_maxlifetime',7200);# 2 hours.
ini_set('session.gc_probability', '1'); #default PHP value.
ini_set('session.gc_divisor', '100'); #default PHP value.
/*====================================================================
ini_set('session.cookie_lifetime', '0');
User cookie life time in seconds.
0 means the cookie wont expire until the user closes the broswer
ini_set('session.gc_maxlifetime',7200); #default: 1440 (24 mins).
Session Garbage Collection cleaner (GC).
7200(seconds) equals to (2 hours): The GC will try to
clean session data in the server for (users who logged
out, closed the browser AND users who are inactive for
more than that time) however the clean function does
not run directly, read the next block for more explaination.
PHP manual:
session.gc_maxlifetime specifies the number of
seconds after which data will be seen as 'garbage'
and potentially cleaned up. Garbage collection may
occur during session start
(depending on session.gc_probability and session.gc_divisor).
ini_set('session.gc_probability', '1'); #default PHP value (1).
ini_set('session.gc_divisor', '100'); #default PHP value (100).
Garbage Collection (GC) Settings:
PHP manual:
session.gc_divisor coupled with
session.gc_probability defines the probability
that the gc (garbage collection) process is started
on every session initialization. The probability is
calculated by using gc_probability/gc_divisor
e.g. 1/100 means there is a 1% chance that the GC
process starts on each request.
session.gc_divisor defaults to 100.
====================================================================*/
/*
HOW TO USE:
- include the session file in all your files and call the session object
require_once('session.class.php');
$session = new Session();
GET SESSION ID:
- $session->sid;
#return type (string)
#example:
echo $session->sid;
GENEREATE NEW SESSION ID:
- $session->re();
#return type (string)
#note: returns the value of the new session id.
#example:
$sid = $session->sid;
$new_sid = $session->re();
echo "My Session ID is: {$sid} but I got a new one now: {$new_sid};
ASSIGN NEW SESSION VALUE:
- $session->set($key,$value);
#return type (void)
#examples:
$session->set("name","foo bar");
$session->set("age",24);
$session->set("auth",TRUE);
GET SESSION VALUE:
- $session->get($key);
#return type (boolean, int, string, array).
#note: returns FALSE if the value is not set
#examples:
echo $session->get("name");
if($session->get("auth")) echo "hello authorized user!";
if(($age = $session->get("age")) > 21)
echo "your age is {$age}, you can drive!";
DELETE SESSION VALUE:
- $session->delete($key);
#return type (void);
#example
$session->delete("age");
DESTROY SESSION
- $session->destroy();
#return type (void);
*/
/*==================================================================*/
class Session{
public $sid;
public function __construct() {
#session_start();
$this->sid = session_id();
}
public function re(){
#session_regenerate_id();
$this->sid = session_id();
return $this->sid;
}
public function set($key, $val) {
$_SESSION[$key] = $val;
return true;
}
public function get($key) {
if ( isset($_SESSION[$key]) ) {
return $_SESSION[$key];
}
return false;
}
public function delete($key) {
unset($_SESSION[$key]);
}
public function destroy() {
$_SESSION = array();
session_destroy();
}
}
?>
FILE: member.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
/*
file: secure.php, profile.php, member.php
authorized (logged in) users => log them out and show goodbye msg or send them to login.php
unauthorized (guests) users => redirect them to login.php
*/
require_once('session.class.php');
$session = new Session();
#if user is not logged in, he will be sent to the login.php page
#note the (!) sign before the $session, it means if the $session->get("auth") == false
if(!$session->get("auth")) header("location:teacherlogin.php");
echo "hello, you are logged in";
echo "<br />";
echo "username: ".$session->get("teacherusername");
echo "<br />";
echo "teacherid: ".$session->get("teacherid");
echo "<br />";
echo "active status: ".$session->get("active") ? "Active" : "Not Active";
echo "<br />";
echo "<a href='logout.php'>Log out</a>";
?>
FILE : logout.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('session.class.php');
$session = new Session();
if($session->get("auth")){
session_destroy();
$msg = "You have been Logged Out | <a href='./home.php'>Home</a>";
}else{
$msg = "You were not logged in, so you cant logout";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Menu</title>
<link rel="stylesheet" type="text/css" href="menu.css">
</head>
<?php
include('noscript.php');
?>
<body>
<?= $msg ? $msg : '' ?>
</body>
</html>
FILE: login.php
<?php
/*
file: login.php
authorized (logged in) users must be redirected to a secure page (member.php) or (secure.php)
unauthorized (guests) users have to see the login form
*/
#include the class file and start it.
require_once('session.class.php');
$session = new Session();
#check user's access
if($session->get("auth"))header("location:member.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
// connect to the database
#include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
// required variables (make them explciit no need for foreach loop)
if (isset($_POST['submit'])) {
$teacherusername = (isset($_POST['teacherusername'])) ? $_POST['teacherusername'] : '';
$teacherpassword = md5(md5("g3f".$_POST['teacherpassword']."rt4"));
// don't use $mysqli->prepare here
$query = "SELECT TeacherId, TeacherForename, TeacherSurname, TeacherUsername, TeacherPassword, Active FROM Teacher WHERE TeacherUsername = ? AND TeacherPassword = ? LIMIT 1";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ss",$teacherusername,$teacherpassword);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbTeacherId, $dbTeacherForename,$dbTeacherSurname,$dbTeacherUsername,$dbTeacherPassword, $dbActive);
while($stmt->fetch()) {
if ($teacherusername == $dbTeacherUsername && $teacherpassword == $dbTeacherPassword) {
if ($dbActive == 0) {
$error = "You Must Activate Your Account from Email to Login";
}else{
$session->set('auth',TRUE);
$session->set('active',TRUE);
$session->set('teacherid',$dbTeacherId);
$session->set('teacherusername',$dbTeacherUsername);
header('Location: member.php') ;
}
}else{
//password and username dont match
$error = "The Username or Password that you Entered is not Valid. Try Entering it Again";
}
}
/* close statement */
$stmt->close();
/* close connection */
$mysqli->close();
}
?>

Categories