Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

User login authentication 1

Status
Not open for further replies.

hex6007

MIS
Sep 2, 2008
53
PH
please help how to check if the user or redirect the user to the login page first before going to my homepage.

thanks in advance.
 
You need to make a session.

Make a file called approve.php
Code:
<?php
session_start();
if (!isset($_SESSION['phplogin'])
    || $_SESSION['phplogin'] !== true) {
    header('Location: login.php'); //Replace that if login.php is somewhere else
    exit;
}
?>

part.
then on all other pages that you need to be logged in to show add:
Code:
<?php session_start(); require 'approve.php'; ?>

also on your login page you need to add session_start... something like this:

Code:
<?php
session_start();
if(isset($_POST['login']))
{
$password = $_POST['pswd'];
if ( $password == "mypassword" ) { //Replace mypassword with your password it login
    $_SESSION['phplogin'] = true;
    header('Location: index.php'); //Replace index.php with what page you want to go to after succesful login
    exit;
} else {
?>

of course, you will need to tweak it if you're going to use a sql database to get passwords.
But that's a start anyhow :)
 
@Zhris

i would say that the link you posted is not a good example. It does not follow good sql practice, makes assumptions about php.ini settings (which are likely to be untrue) and uses deprecated function calls.

Additionally, it does not follow good practice for destroying a session. and although it briefly mentions encryption of password data, it does not explain properly what to do about it.
 
i'd also add that i personally would not like something as trivial as login management to take up three separate files. IMO, it should be done as one file and that this file should be 'required' at the start of each page.
 
@jpadie

I am unfamiliar with sufficient sql and session practices. I used this script a long time ago and edited it to destroy sessions properly and encrypt password data. Since then I have seen other scripts and notice how different their methods are. I partially hoped for a response like that as I was unsure how well written the code was. With so many scripts, written in different ways, I really don't know which one to choose etc. Do you have a link to a very good/secure example as this is an important issue to me?

Thanks,

Chris
 
i'll post something a bit later. i've half written some code and would welcome critique on it.
 
this code is genuinely not tested. it's probably full of syntax errors etc as i've been typing it whilst watching an hour of telly. pls provide feedback into this thread and i'll fix the bugs as we go.

this code supports any database supported by the PDO extension and also php5 only. The create statements for each database type are different so be sure to edit the sample sql for your chosen engine.

here it is! Just store in a php file and add this code to any page you wish to protect. remember to set all the parameters too

Code:
<?php require_once 'activeUser.php'; ?>

Code:
<?php
/*
 * CONFIG
 * 
 */
define ('TIMEOUT', 			1);			//define the login timeout in minutes set to zero for no timeout
define ('ALLOWREMEMBERME', 	true); 		//to allow users to select to avoid login through remember me function
define ('COOKIEDURATION', 	100); 		//define the amount of time that the browser remembers the user
define ('SALT', 			'3434jbnhkef'); //random characters for hashing

/**
 * sample sql
	create table if not exists TABLENAME (
 				userID INT(10) AUTO_INCREMENT PRIMARY KEY , 
 				loginID varchar(255) UNIQUE, 
 				pwd varchar(255)
			)
 */
class activeUser{
	
	public function __construct(){
		$sitename = ''; //name of the site
		
		//set these for username pwd based database connections
		$username = null;
		$password = null;
		
		$userTable  = ''; //enter the table name for the databse
		
		//mysql dsn looks like this mysql:host=hostname;dbname=testdatabase
		//see here for more details [URL unfurl="true"]http://fr2.php.net/manual/en/ref.pdo-mysql.connection.php[/URL]
		$dsn = '';
		
		try{
			$this->pdo = new PDO ($dsn, $username, $password); //your dsn goes here
		} catch (PDOException $e){
			die ('Cannot connect: ' . $e->getMessage());
		}
		$this->startUp();
	}	

	public function startUp(){
		
		if ($this->isLogOutRequest()){
			$this->logOut();
		}elseif ($this->isLogOnRequest()){
			if ($this->isValidUser()){
				$this->logIn();
				$this->checkRememberMe();
			} else {
				$this->logOut();
				session_write_close();
				exit();
			}
		} elseif ($this->isLoggedIn()){
			$this->logIn();
		} elseif ($this->isRememberedUser()){
			$this->logIn();
			$this->checkRememberMe();
		} else{
			$this->logOut();
			session_write_close();
			exit();
		}
	}
	
	private function logIn(){
		$_SESSION['activeUser']['loggedIn'] = true;
		$_SESSION['activeUser']['lastAccess'] = time();
	}
	
	private function logOut(){
		unset ($_SESSION['activeUser']);
		$this->removeRememberMeCookie();
		$this->displayLoginForm();
	}
	
	private function isLogOutRequest(){
		if (isset($_GET['action']) && $_GET['action'] == 'logout'){
			return true;
		} else {
			return false;
		}
	}
	
	private function isRememberedUser(){
		if (defined('ALLOWREMEMBERME') && ALLOWREMEMBERME === TRUE){
			if (isset($_COOKIE['forgetmenot'])){
				$data = unserialize($_COOKIE['forgetmenot']);
				list ($this->userID, $this->pwd) = $data;
				
				//just get user name based responses
				$sql = "select pwd as c from {$this->userTable} where userID=?";
				$params = array ($this->userID);
				
				$s = $this->db->prepare($sql);
				$s->execute($params);
				$row = $s->fetchAll();
				
				if (count($row) !== 1){
					$this->errorMessages[] = "Sorry, either this is a spoof login attempt or your user account has been deleted or suspended since your last visit";
					return false;
				} else {
					//check the password
					$pwd = $row[0][pwd];
					if ( $this->encrypt($pwd . $this->encrypt(SALT)) == $this->pwd){
						$_SESSION['activeUser']['userID'] = $this->userID;
						return true;
						
					} else {
						$this->errorMessages = "Sorry, the automatically supplied password was incorrect";
						return false;
					}
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	private function setRememberMeCookie(){
		$expire = time() + (COOKIEDURATION * 24 * 60 * 60);
	    $cookie_pass = $this->encrypt( $this->encrypt($this->pwd) . $this->encrypt(SALT) );
		$cookiedata  = serialize(array($this->userID, $cookie_pass));
	    setcookie('forgetmenot', $cookiedata, $expire);		
	}
	
	private function removeRememberMeCookie(){
		if (isset($_COOKIE['forgetmenot'])){
			$expire = time() - 3600;
			$cookiedata = serialize (array('',''));
			setcookie('forgetmenot', $cookiedata, $expire);		
		}
	}
	
	private function checkRememberMe(){
		if (defined('ALLOWREMEMBERME') && ALLOWREMEMBERME===TRUE){
			if (isset($_POST['rememberme'])){
				$this->setRememberMeCookie();
			} else {
				$this->removeRememberMeCookie();
			}
		} elseif(defined('ALLOWREMEMBERME') AND ALLOWREMEMBERME=== FALSE) {
			$this->removeRememberMeCookie();
		}
	}
	
	private function formValidates(){
		if (empty($_POST['loginID']) || empty($_POST['pwd'])){
			return false;
		} else {
			$this->loginID = $_POST['loginID'];
			$this->pwd = $_POST['pwd'];
			return true;
		}
	}
	
	private function isValidUser(){
		if (!$this->formValidates()){
			$this->errorMessages[] = "You have not supplied either a username or a password";
			$this->logout();
		}
		if (!$this->checkNonce('logIn')){
			$this->errorMessages[] = "You cannot login through using the back button or refresh";
			$this->logOut();
		}
		$sql = "SELECT userID from {$this->userTable} where loginID=? and pwd=? ";
		$params = array (	$this->loginID, 
							$this->encrypt($this->pwd),
						);
		$s = $this->pdo->prepare($sql);
		$s->execute($params);
		$results = $s->fetchAll();
		if (count($results) === 1){
			$userID = $results[0][0];
			$_SESSION['activeUser']['userID'] = $userID;
			return true;
		} else {
			$this->errorMessages[] = "Either your username or password is incorrect";
			return false;
		}
	}
	
	private function isLogOnRequest(){
		if (isset($_POST['action']) && ($_POST['action'] === 'logIn')){
			return true;
		} else {
			return false;
		}
	}
	
	private function isLoggedIn(){
		if (isset($_SESSION['activeUser']['loggedIn']) && $_SESSION['activeUser']['loggedIn'] === true){
			if ($this->sessionTimedOut()){
				$this->errorMessages[] = "Your login session has timed out. Please log in again";
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}
	
	private function sessionTimedOut(){
		if (defined('TIMEOUT') && TIMEOUT > 0){
			if (  ($_SESSION['activeUser']['lastAccess'] + ( TIMEOUT * 60) ) < time() ){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	private function encrypt($val){
		return sha1($val);
	//	return $val;
	}
	
	private function getErrorMessage(){
		$message = '';
		foreach ($this->errorMessages as $msg) {
			$message .= <<<HTML
	<p class="message">$msg</p>

HTML;
		}
		return empty($message) ? null : "<div class=\"messages\">\r\n" . $message . "</div>";
	}
	
	private function getNonce($type='default'){
		if (isset($_SESSION['activeUser']['nonce'][$type])){
			//
		} else {
			$_SESSION['activeUser']['nonce'][$type] = sha1 (uniqid('nonce', true));
		}
		return $_SESSION['activeUser']['nonce'][$type] ;
	}
	
	private function checkNonce($type='default'){
		if (empty($_SESSION['activeUser']['nonce'][$type])){
			return false;
		}
		if (empty($_REQUEST['activeUser']['nonce'])){
			return false;
		}
		if ($_SESSION['activeUser']['nonce'][$type] == $_POST['nonce']){
			unset ($_SESSION['activeUser']['nonce'][$type]);
			return true;
		} else {
			return false;
		}
	}
	
	private function rememberMeCheckBox(){
		if (defined('ALLOWREMEMBERME') && ALLOWREMEMBERME===true) {
			return <<<HTML
	<p class="forgetmenot">
		<label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> Remember Me</label>
	</p>
HTML;
		}
	}
	
	private function insertNonceField($type){
		$value = $this->getNonce($type);
		return <<<HTML
	<input type="hidden" name="nonce" value="$value" />
HTML;
	}

	private function displayLoginForm(){
		echo <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] dir="ltr" lang="en-US">
<head>
	<title>{$this->sitename} - Login</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<script type="text/javascript">
		function focusit() {
			document.getElementById('user_login').focus();
		}
		window.onload = focusit;
	</script>
</head>
<body class="login">

<div id="login">
	<h1>{$this->sitename}</h1>
	{$this->getErrorMessage()}
	<form name="loginform" id="loginform" action="index.php" method="post">
		<p>
			<label>Username<br />
			<input type="text" name="loginID" id="user_login" class="input" value="" size="20" tabindex="10" /></label>
		</p>
		<p>
			<label>Password<br />
	
			<input type="password" name="pwd" id="user_pass" class="input" value="" size="20" tabindex="20" /></label>
		</p>
		{$this->rememberMeCheckBox()}
		<p class="submit">
			<input type="submit" name="wp-submit" id="wp-submit" value="Log In" tabindex="100" />
			<input type="hidden" name="action" value="logIn" />
			{$this->insertNonceField('logIn')}
		</p>
	
	</form>
</div>
</body>
</html>
HTML;
	}
}

if (session_id() == '' ) {
	session_start();
}
$activeUser = new activeUser();

echo "If you are seeing this then you are logged in";
?>
 
i've done a bit of testing and corrected some bugs. the new code is posted below.

additionally, for those people who do not have PDO installed i have also written a form of reverse abstraction class. just add this in to the login file and it will all work fine.

i appreciate that this class is length but it as quite a bit of functionality, it handles session time outs, rememberme and more.

Code:
<?php
/*
 * CONFIG
 * 
 */
define ('TIMEOUT', 			1);			//define the login timeout in minutes set to zero for no timeout
define ('ALLOWREMEMBERME', 	true); 		//to allow users to select to avoid login through remember me function
define ('COOKIEDURATION', 	100); 		//define the amount of time in days that the browser remembers the user
define ('SALT', 			'3434jbnhkef'); //random characters for hashing

/**
 * sample sql
	create table if not exists users (
 				userID INT(10) AUTO_INCREMENT PRIMARY KEY , 
 				loginID varchar(255) UNIQUE, 
 				pwd varchar(255)
			)
 */
class activeUser{
	private $errorMessages = array();
	
	public function __construct(){
		$this->sitename = 'MySite'; //name of the site
		
		//set these for username pwd based database connections
		$username = 'root';
		$password = 'root';
		
		$this->userTable  = 'users'; //enter the table name for the databse
		
		//mysql dsn looks like this mysql:host=hostname;dbname=testdatabase
		//see here for more details [URL unfurl="true"]http://fr2.php.net/manual/en/ref.pdo-mysql.connection.php[/URL]
		$dsn = 'mysql:host=localhost;dbname=test';
		
		try{
			$this->pdo = new PDO ($dsn, $username, $password); //your dsn goes here
		} catch (PDOException $e){
			die ('Cannot connect: ' . $e->getMessage());
		}
		$this->startUp();
	}	

	public function startUp(){
		
		if ($this->isLogOutRequest()){
			$this->logOut();
		}elseif ($this->isLogOnRequest()){
			if ($this->isValidUser()){
				$this->logIn();
				$this->checkRememberMe();
			} else {
				$this->logOut();
				session_write_close();
				exit();
			}
		} elseif ($this->isLoggedIn()){
			$this->logIn();
		} elseif ($this->isRememberedUser()){
			$this->logIn();
			$this->checkRememberMe();
		} else{
			$this->logOut();
		}
	}
	
	private function logIn(){
		$_SESSION['activeUser']['loggedIn'] = true;
		$_SESSION['activeUser']['lastAccess'] = time();
	}
	
	private function logOut(){
		unset ($_SESSION['activeUser']);
		$this->removeRememberMeCookie();
		$this->displayLoginForm();
	}
	
	private function isLogOutRequest(){
		if (isset($_GET['action']) && $_GET['action'] == 'logout'){
			return true;
		} else {
			return false;
		}
	}
	
	private function isRememberedUser(){
		if (defined('ALLOWREMEMBERME') && ALLOWREMEMBERME === TRUE){
			if (isset($_COOKIE['forgetmenot'])){
				$data = unserialize($_COOKIE['forgetmenot']);
				list ($this->userID, $this->pwd) = $data;
				
				//just get user name based responses
				$sql = "select pwd as c from {$this->userTable} where userID=?";
				$params = array ($this->userID);
				
				$s = $this->db->prepare($sql);
				$s->execute($params);
				$row = $s->fetchAll();
				
				if (count($row) !== 1){
					$this->errorMessages[] = "Sorry, either this is a spoof login attempt or your user account has been deleted or suspended since your last visit";
					return false;
				} else {
					//check the password
					$pwd = $row[0][pwd];
					if ( $this->encrypt($pwd . $this->encrypt(SALT)) == $this->pwd){
						$_SESSION['activeUser']['userID'] = $this->userID;
						return true;
						
					} else {
						$this->errorMessages = "Sorry, the automatically supplied password was incorrect";
						return false;
					}
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	private function setRememberMeCookie(){
		$expire = time() + (COOKIEDURATION * 24 * 60 * 60);
	    $cookie_pass = $this->encrypt( $this->encrypt($this->pwd) . $this->encrypt(SALT) );
		$cookiedata  = serialize(array($this->userID, $cookie_pass));
	    setcookie('forgetmenot', $cookiedata, $expire);		
	}
	
	private function removeRememberMeCookie(){
		if (isset($_COOKIE['forgetmenot'])){
			$expire = time() - 3600;
			$cookiedata = serialize (array('',''));
			setcookie('forgetmenot', $cookiedata, $expire);		
		}
	}
	
	private function checkRememberMe(){
		if (defined('ALLOWREMEMBERME') && ALLOWREMEMBERME===TRUE){
			if (isset($_POST['rememberme'])){
				$this->setRememberMeCookie();
			} else {
				$this->removeRememberMeCookie();
			}
		} elseif(defined('ALLOWREMEMBERME') AND ALLOWREMEMBERME=== FALSE) {
			$this->removeRememberMeCookie();
		}
	}
	
	private function formValidates(){
		if (empty($_POST['loginID']) || empty($_POST['pwd'])){
			return false;
		} else {
			$this->loginID = $_POST['loginID'];
			$this->pwd = $_POST['pwd'];
			return true;
		}
	}
	
	private function isValidUser(){
		if (!$this->formValidates()){
			$this->errorMessages[] = "You have not supplied either a username or a password";
			$this->logOut();
		}
		if (!$this->checkNonce('logIn')){
			$this->errorMessages[] = "You cannot login through using the back button or refresh";
			$this->logOut();
		}
		$sql = "SELECT userID from {$this->userTable} where loginID=? and pwd=? ";
		$params = array (	$this->loginID, 
							$this->encrypt($this->pwd),
						);
		$s = $this->pdo->prepare($sql);
		$s->execute($params);
		$results = $s->fetchAll();
		if (count($results) === 1){
			$userID = $results[0][0];
			$_SESSION['activeUser']['userID'] = $userID;
			return true;
		} else {
			$this->errorMessages[] = "Either your username or password is incorrect";
			return false;
		}
	}
	
	private function isLogOnRequest(){
		if (isset($_POST['action']) && ($_POST['action'] === 'logIn')){
			return true;
		} else {
			return false;
		}
	}
	
	private function isLoggedIn(){
		if (isset($_SESSION['activeUser']['loggedIn']) && $_SESSION['activeUser']['loggedIn'] === true){
			if ($this->sessionTimedOut()){
				$this->errorMessages[] = "Your login session has timed out. Please log in again";
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}
	
	private function sessionTimedOut(){
		if (defined('TIMEOUT') && TIMEOUT > 0){
			if (  ($_SESSION['activeUser']['lastAccess'] + ( TIMEOUT * 60) ) < time() ){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	private function encrypt($val){
		return sha1($val);
	//	return $val;
	}
	
	private function getErrorMessage(){
		$message = '';
		foreach ($this->errorMessages as $msg) {
			$message .= <<<HTML
	<p class="message">$msg</p>

HTML;
		}
		return empty($message) ? null : "<div class=\"messages\">\r\n" . $message . "</div>";
	}
	
	private function getNonce($type='default'){
		if (isset($_SESSION['activeUser']['nonce'][$type])){
			//
		} else {
			$_SESSION['activeUser']['nonce'][$type] = sha1 (uniqid('nonce', true));
		}
		return $_SESSION['activeUser']['nonce'][$type] ;
	}
	
	private function checkNonce($type='default'){
		if (empty($_SESSION['activeUser']['nonce'][$type])){
			return false;
		}
		if (empty($_REQUEST['nonce'])){
			return false;
		}
		if ($_SESSION['activeUser']['nonce'][$type] == $_POST['nonce']){
			unset ($_SESSION['activeUser']['nonce'][$type]);
			return true;
		} else {
			return false;
		}
	}
	
	private function rememberMeCheckBox(){
		if (defined('ALLOWREMEMBERME') && ALLOWREMEMBERME===true) {
			return <<<HTML
	<p class="forgetmenot">
		<label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> Remember Me</label>
	</p>
HTML;
		}
	}
	
	private function insertNonceField($type){
		$value = $this->getNonce($type);
		return <<<HTML
	<input type="hidden" name="nonce" value="$value" />
HTML;
	}

	private function displayLoginForm(){
		echo <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] dir="ltr" lang="en-US">
<head>
	<title>{$this->sitename} - Login</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<script type="text/javascript">
		function focusit() {
			document.getElementById('user_login').focus();
		}
		window.onload = focusit;
	</script>
</head>
<body class="login">

<div id="login">
	<h1>{$this->sitename}</h1>
	{$this->getErrorMessage()}
	<form name="loginform" id="loginform" action="{$_SERVER['PHP_SELF']}" method="post">
		<p>
			<label>Username<br />
			<input type="text" name="loginID" id="user_login" class="input" value="" size="20" tabindex="10" /></label>
		</p>
		<p>
			<label>Password<br />
	
			<input type="password" name="pwd" id="user_pass" class="input" value="" size="20" tabindex="20" /></label>
		</p>
		{$this->rememberMeCheckBox()}
		<p class="submit">
			<input type="submit" name="wp-submit" id="wp-submit" value="Log In" tabindex="100" />
			<input type="hidden" name="action" value="logIn" />
			{$this->insertNonceField('logIn')}
		</p>
	
	</form>
</div>
</body>
</html>
HTML;
	exit;
	}
}
if (session_id() == '' ) {
	session_start();
}
$activeUser = new activeUser();

echo "If you are seeing this then you are logged in";

and for the non-PDO users

Code:
if (!class_exists('PDO')){
	
	class PDO{
		private $dbLink;
		
		public function __construct($dsn, $username, $password){
			$t = preg_match ('/^mysql:host=(.*?);dbname=(.*?)$/imsx', $dsn, $match);
			if (!$t){
				throw new PDOException('The DSN is not properly constructed');
				return false;
			}
			$this->dbLink = mysql_connect($match[1]);
			if (!$this->dbLink) {
				throw new PDOException(mysql_error());
				return false;
			}
			if (!mysql_select_db($match[2], $this->dbLink)){
				throw new PDOException(mysql_error());
				return false;
			}
			return true;
		}
		
		public function prepare ($query){
			return new PDO_statement($query, $this->dbLink);
		}
		
	}
	
	class PDO_statement{
		public function __construct ($query, $dbh){
			$this->result = array();
			
			mysql_query("SET @q = '$query'" ) or die(mysql_error());
			mysql_query("PREPARE STMNT FROM @q") or die(mysql_error());
		}
		
		public function execute($params = array()){
			$i = 0;
			$using = array();
			foreach($params as $param){
				mysql_query("SET @a{$i} = '$param'") or die(mysql_error());
				$using[] = "@a{$i}";
				$i++;
			}
			if ($i > 0){
				$result = mysql_query("EXECUTE STMNT USING " . implode(',', $using));
			} else{
				$result = mysql_query("EXECUTE STMNT");
			}
			if (!$result){
				die(mysql_error());
			}
			while ($row = mysql_fetch_array($result)){
				$this->result[] = $row;
			}
			mysql_query('DEALLOCATE STMNT');
		}
		
		public function fetchAll(){
			return $this->result;
		}
	}
	
}
if (!class_exists('PDOException')){
	class PDOException extends Exception{
		public function __construct($message , $code=0){
			parent::__construct ($message, $code);
		}
	}
}
 
Thanks for your example, it looks efficient to me. I'm unsure what you mean by:

just add this in to the login file and it will all work fine.

The login is part of activeUser.php? Can you explain again where the form of reverse abstraction class goes?

Chris
 
Unfortunately I couldn't get this working at all. I recieve all sorts of syntax errors, which I have tried fixing however they seem endless probably because I have made a critical mistake. Literally I added the non pdo to the end of the file, changed all the db info etc etc. Seems like a nice example and would love to get it running.

Chris
 
Chris

I don't get syntax errors, so maybe there is a difference between our setups.

can you let me know what errors you receive? If you would rather do this offline then you can find me email address on my site. We can post the final version once settled.
 
To jpadie,

im new to php and im study the code you've posted. honestly, im getting to understand php code base on the one you've given..and i dont want to go out of the "box"... I was given module pages and need to put a log in authentication on it. can you please give me code on this for newbeez like me.

thanks in advance.
 
@hex6007

my code 'plugs and plays'. it's fine for newbies as well as anyone else.

If you are having trouble using it, please post back here with your issues, together with error codes etc.
 
Jpadie, with your last code for the PDO users, how would I request the code to connect to my DB and check if the username and password exist in a table? (varify the username & password against a user in my DB) ?

Thank for the awesome script!
 
irrespective of whether or not you use PDO (assuming you use the PDO mimic script if you don't have PDO), then the method that performs the database look up is called isValidUser().

the script relies on fields being received in the POST superglobal called loginID and pwd. You set the database connection parameters in the __construct() method.
 
Thanks Jpadie,

Here's what that section looks like now

Code:
 public function __construct(){
        $this->sitename = 'MySite'; //name of the site
        
        //set these for username pwd based database connections
        $username = 'myusername';
        $password = 'canttellyoudat';
        
        $this->userTable  = 'choir_list'; //enter the table name for the databse
        
        //mysql dsn looks like this mysql:host=hostname;dbname=testdatabase
        //see here for more details [URL unfurl="true"]http://fr2.php.net/manual/en/ref.pdo-mysql.connection.php[/URL]
        $dsn = 'mysql:host=88.208.944.324;dbname=mydatabase';

Now all I get is that, the username and or password is not valid message even though the username and password are valid and exist. Any more ideas?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top