PHP - MySQL Login using sessions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sn202
Forum Commoner
Posts: 36
Joined: Thu Dec 16, 2004 7:30 pm

PHP - MySQL Login using sessions

Post by sn202 »

Hi all,

Right, basically I have the following script using sessions to implement a login feature and then redirect the user to the appropriate part of the site according to their "role", however, at present it is just sitting there doing nothing (although I do know it is getting to the end of my script as it was throwing up an error about a missing "}" in my redirect function.)

any help with this will much appreciated,

Regards,

Simon.

Code: Select all

<?php 
error_reporting(E_ALL); 
#connect to MYSQL 
$conn = @mysql_connect( "linuxproj", "****", "****" ) 
or die( mysql_error()  ); 
#select the specified database 
$rs = @mysql_select_db ( "db_sn202", $conn ) 
or die( mysql_error()  ); 

session_start(); 
function session_defaults() { 
    $_SESSION['logged'] = false; 
    $_SESSION['uid'] = 0; 
    $_SESSION['username'] = ''; 
    $_SESSION['cookie'] = 0; 
    $_SESSION['remember'] = false; 
} 
if (!isset($_SESSION['uid']) ) { 
    session_defaults(); 
} 
class User { 
    var $db = null; // PEAR::DB pointer 
    var $failed = false; // failed login attempt 
    var $date; // current date GMT 
    var $id = 0; // the current user's id 
    function User($db) { 
        $this->db = $db; 
        $this->date = $GLOBALS['date']; 
        if ($_SESSION['logged']) { 
            $this->_checkSession(); 
        } elseif ( isset($_COOKIE['mtwebLogin']) ) { 
            $this->_checkRemembered($_COOKIE['mtwebLogin']); 
        } 
    } 
    function _checkLogin($username, $password, $remember) { 
        $username = $this->db->quote($username); 
        $password = $this->db->quote(md5($password)); 
        $sql = "SELECT * FROM user WHERE " . 
        "username = $username AND " . 
        "password = $password"; 
        $result = $this->db->getRow($sql); 
        if ( is_object($result) ) { 
            $this->_setSession($result, $remember); 
            header("location:test.php"); 
            return true; 
        } else { 
            $this->failed = true; 
            $this->_logout(); 
            return false; 
        } 
    } 
    function _setSession($values, $remember, $init = true) { 
        $this->id = $values->id; 
        $_SESSION['uid'] = $this->id; 
        $_SESSION['username'] = htmlspecialchars($values->username); 
        $_SESSION['cookie'] = $values->cookie; 
        $_SESSION['logged'] = true; 
        if ($remember) { 
            $this->updateCookie($values->cookie, true); 
        } 
        if ($init) { 
            $session = $this->db->quote(session_id()); 
            $ip = $this->db->quote($_SERVER['REMOTE_ADDR']); 

            $sql = "UPDATE user SET session = $session, ip = $ip WHERE " . 
            "id = $this->id"; 
            $this->db->query($sql); 
        } 
    } 
    function updateCookie($cookie, $save) { 
        $_SESSION['cookie'] = $cookie; 
        if ($save) { 
            $cookie = serialize(array($_SESSION['username'], $cookie) ); 
            set_cookie('mtwebLogin', $cookie, time() + 31104000, '/directory/'); 
        } 
    } 
    function _checkRemembered($cookie) { 
        list($username, $cookie) = @unserialize($cookie); 
        if (!$username or !$cookie) return; 
        $username = $this->db->quote($username); 
        $cookie = $this->db->quote($cookie); 
        $sql = "SELECT * FROM user WHERE " . 
        "(username = $username) AND (cookie = $cookie)"; 
        $result = $this->db->getRow($sql); 
        if (is_object($result) ) { 
            $this->_setSession($result, true); 
        } 
    } 
    function _checkSession() { 
        $username = $this->db->quote($_SESSION['username']); 
        $cookie = $this->db->quote($_SESSION['cookie']); 
        $session = $this->db->quote(session_id()); 
        $ip = $this->db->quote($_SERVER['REMOTE_ADDR']); 
        $sql = "SELECT * FROM user WHERE " . 
        "(username = $username) AND (cookie = $cookie) AND " . 
        "(session = $session) AND (ip = $ip)"; 
        $result = $this->db->getRow($sql); 
        if (is_object($result) ) { 
            $this->_setSession($result, false, false); 
        } else { 
            $this->_logout(); 
        } 
    } 
    function _redirect() { 
        $name     = $_POST['username']; 
        $self       =    $_SERVER['PHP_SELF']; 
        $referer  =    $_SERVER['HTTP_REFERER']; 
        $sql2="select role from user where username='$name'"; 
        #exercute the query 
        $rs2 = mysql_query( $sql2, $conn ) 
        or die( mysql_error() ); 
        $row = mysql_fetch_object($rs2); 
        #get number of rows that match username 
        $num = mysql_numrows( $rs2 ); 
        #if there is a match the login is authenticated 
        if( $num > 0 ) 
        { $msq = "Welcome $name - your log-in succeeded"; } 
        if ($row->role == "admin") { 
            header("HTTP/1.1 301 Moved Permanently"); 
            header ("Location: http://www.ecs.soton.ac.uk/~sn202/fyp/admin/"); 
            header("Connection: close"); 
        } 
        if ($row->role == "learner") { 
            header("HTTP/1.1 301 Moved Permanently"); 
            header ("Location: http://www.ecs.soton.ac.uk/~sn202/fyp/learner/"); 
            header("Connection: close"); 
        } 
        if ($row->role == "instructor") { 
            header("HTTP/1.1 301 Moved Permanently"); 
            header ("Location: http://www.ecs.soton.ac.uk/~sn202/instructor/"); 
            header("Connection: close"); 
        } 
    } 
} 
?>
feyd | you can use

Code: Select all

now.[/color]
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Well, part of the problem is that you're not actually initializing the class. Classes are blueprints: you must create the actual object in your script afterwards.
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

Aye... let me try to reitterate what he just said.

Are you just trying to run this class file and see if it returns anything? If so, then as he said, you have to initiate it and then call the functions you want...

ie :

Code: Select all

&lt;?php
include('classname.php');
$a=new User;
$a-&gt;updateCookie($foo,$bar);

//..etc..
?&gt;

feyd | ;)


however... I think that you are most definately aware of this need and are just having a problem in your code...

So, #1 what post data are you getting?

Secondly, try putting Or die at the end of EVERY sql query and statement (ie even the mysql_fetch_assoc()) and see what ya get as you could have a sql failure somewhere and not even know it...

Lastly, put little javascript Alert messages about every 10 lines just to see if it's even being executed and where it's stopping/skipping. that should help you a lot in debugging...

Other than that, without seeing how you are passing data to this class, i don't really see a problem with your code...


edit : thnx feyd ;) keep forgetting to use that... lol

minor improvement you could make :

Code: Select all

//.....
if ($row-&gt;role == &quote;admin&quote;) { 
header(&quote;HTTP/1.1 301 Moved Permanently&quote;); 
header (&quote;Location: http://www.ecs.soton.ac.uk/~sn202/fyp/admin/&quote;); 
header(&quote;Connection: close&quote;); 
} 
if ($row-&gt;role == &quote;learner&quote;) { 
header(&quote;HTTP/1.1 301 Moved Permanently&quote;); 
header (&quote;Location: http://www.ecs.soton.ac.uk/~sn202/fyp/learner/&quote;); 
header(&quote;Connection: close&quote;); 
} 
if ($row-&gt;role == &quote;instructor&quote;) { 
header(&quote;HTTP/1.1 301 Moved Permanently&quote;); 
header (&quote;Location: http://www.ecs.soton.ac.uk/~sn202/instructor/&quote;); 
header(&quote;Connection: close&quote;); 
} 
//....
could be rewritten (and eaiser to manage) with a switch

Code: Select all

&lt;?php
//....

Switch($row-&gt;role)
{
    Case 'admin' :
           header(&quote;HTTP/1.1 301 Moved Permanently&quote;); 
           header (&quote;Location: http://www.ecs.soton.ac.uk/~sn202/fyp/admin/&quote;); 
           header(&quote;Connection: close&quote;); 
    break;
    Case 'leaner' :
           header(&quote;HTTP/1.1 301 Moved Permanently&quote;); 
           header (&quote;Location: http://www.ecs.soton.ac.uk/~sn202/fyp/learner/&quote;); 
           header(&quote;Connection: close&quote;); 
    break;
    Case 'instructor' :
           header(&quote;HTTP/1.1 301 Moved Permanently&quote;); 
           header (&quote;Location: http://www.ecs.soton.ac.uk/~sn202/instructor/&quote;); 
           header(&quote;Connection: close&quote;); 
    break;
}
//.....
?&gt;
of course ya don't have to do this, but it is nice to use switch statements when you are going to have a lot of redundant if's...
sn202
Forum Commoner
Posts: 36
Joined: Thu Dec 16, 2004 7:30 pm

Post by sn202 »

Hi, yeah I have a file, which is initiating the class and I've played around with the code and now i'm getting the following error:
Warning: Missing argument 1 for user() in /home/sn202/public_html/fyp/etrain/authenticate.php on line 32
Code again:

Code: Select all

<?php
error_reporting(E_ALL);
#connect to MYSQL
function &db_connect() {
	require_once 'DB.php';
	PEAR::setErrorHandling(PEAR_ERROR_DIE);
	$db_host = 'linuxproj';
	$db_user = '****';
	$db_pass = '****';
	$db_name = 'db_sn202';
	$dsn = "mysql://$db_user:$db_pass@unix+$db_host/$db_name";
	$db = DB::connect($dsn);
	$db->setFetchMode(DB_FETCHMODE_OBJECT);
	return $db;
}
session_start();
function session_defaults() {
	$_SESSION['logged'] = false;
	$_SESSION['uid'] = 0;
	$_SESSION['username'] = '';
	$_SESSION['cookie'] = 0;
	$_SESSION['remember'] = false;
}
if (!isset($_SESSION['uid']) ) {
	session_defaults();
}
class User {
	var $db = null; // PEAR::DB pointer
	var $failed = false; // failed login attempt
	var $date; // current date GMT
	var $id = 0; // the current user's id
	function User($db) {           
		$this->db = $db;
		$this->date = $GLOBALS['date'];
		if ($_SESSION['logged']) {
			$this->_checkSession();
		} elseif ( isset($_COOKIE['mtwebLogin']) ) {
			$this->_checkRemembered($_COOKIE['mtwebLogin']);
		}
	}
	function _checkLogin($username, $password, $remember) {
		$username = $this->db->quote($username);
		$password = $this->db->quote(md5($password));
		$sql = "SELECT * FROM user WHERE " .
		"username = $username AND " .
		"password = $password";
		$result = $this->db->getRow($sql);
		if ( is_object($result) ) {
			$this->_setSession($result, $remember);
			return true;
		} else {
			$this->failed = true;
			$this->_logout();
			return false;
		}
	}
	function _setSession($values, $remember, $init = true) {
		$this->id = $values->id;
		$_SESSION['uid'] = $this->id;
		$_SESSION['username'] = htmlspecialchars($values->username);
		$_SESSION['cookie'] = $values->cookie;
		$_SESSION['logged'] = true;
		if ($remember) {
			$this->updateCookie($values->cookie, true);
		}
		if ($init) {
			$session = $this->db->quote(session_id());
			$ip = $this->db->quote($_SERVER['REMOTE_ADDR']);

			$sql = "UPDATE user SET session = $session, ip = $ip WHERE " .
			"id = $this->id";
			$this->db->query($sql);
		}
	}
	function updateCookie($cookie, $save) {
		$_SESSION['cookie'] = $cookie;
		if ($save) {
			$cookie = serialize(array($_SESSION['username'], $cookie) );
			set_cookie('mtwebLogin', $cookie, time() + 31104000, '/directory/');
		}
	}
	function _checkRemembered($cookie) {
		list($username, $cookie) = @unserialize($cookie);
		if (!$username or !$cookie) return;
		$username = $this->db->quote($username);
		$cookie = $this->db->quote($cookie);
		$sql = "SELECT * FROM user WHERE " .
		"(username = $username) AND (cookie = $cookie)";
		$result = $this->db->getRow($sql);
		if (is_object($result) ) {
			$this->_setSession($result, true);
		}
	}
	function _checkSession() {
		$username = $this->db->quote($_SESSION['username']);
		$cookie = $this->db->quote($_SESSION['cookie']);
		$session = $this->db->quote(session_id());
		$ip = $this->db->quote($_SERVER['REMOTE_ADDR']);
		$sql = "SELECT * FROM user WHERE " .
		"(username = $username) AND (cookie = $cookie) AND " .
		"(session = $session) AND (ip = $ip)";
		$result = $this->db->getRow($sql);
		if (is_object($result) ) {
			$this->_setSession($result, false, false);
		} else {
			$this->_logout();
		}
	}
	function _redirect() {
		$name     = $_POST['username'];
		$sql2="select role from user where username='$name'";
		#exercute the query
		$rs2 = mysql_query( $sql2, $conn )
		or die( mysql_error() );
		$row = mysql_fetch_object($rs2);
		#get number of rows that match username
		$num = mysql_numrows( $rs2 );
		#if there is a match the login is authenticated
		if( $num > 0 )
		Switch($row->role)
		{
			Case 'admin' :
			header("HTTP/1.1 301 Moved Permanently");
			header ("Location: http://www.ecs.soton.ac.uk/~sn202/fyp/admin/");
			header("Connection: close");
			break;
			Case 'leaner' :
			header("HTTP/1.1 301 Moved Permanently");
			header ("Location: http://www.ecs.soton.ac.uk/~sn202/fyp/learner/");
			header("Connection: close");
			break;
			Case 'instructor' :
			header("HTTP/1.1 301 Moved Permanently");
			header ("Location: http://www.ecs.soton.ac.uk/~sn202/instructor/");
			header("Connection: close");
			break;}
	}
}
?>
Cheers,


Simon.


feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
Post Reply