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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

session logon 1

Status
Not open for further replies.

coolicus

Programmer
May 15, 2007
50
0
0
GB
I am trying to create a simple text field login but am struggling

Code:
<?php
session_start();

if($_POST){
  $_SESSION['username']=$_POST["loginpass"];

}


if(!$_SESSION['username'] == "password"){
  echo "You are not authenticated.  Please login.<br><br>
  
<form action='index.php' method='post'>
<input type='password' name='loginpass' />
<input type='submit' value='log in' />
</form>";

} 			
else
{
echo "logged in, <a href='admin.php'>continue to admin page</a>";
}
				
?>

Can someone tell me what is wrong with this? The password is simply 'password'
 
i suspect it is an issue with the way you are testing for $_POST. check instead for the actual variable.

here is a tweak on your code, also checking for backbutton resubmission and timeouts. set the timeout value you want in the definition at the top of the file.

assuming you name the script 'login.php' to use it, just put
Code:
require_once 'login.php';
at the top of every page you want protected by access control.

Code:
<?php
define ("TIMEOUT", 60) ;// timeout in seconds
start();

function start(){
	if (session_id() == '') session_start(); //start the session if needed
	if (isLoggedIn()){
		if (isset($_GET['logout'])){
			logOut(true);
		} else {
			//do nothing, let script execution continue
			return;
		}
	}
	if (isset($_POST['loginpass'])){
		//validate the password
		if (checkpassword($_POST['loginpass'])){
			//if we have the right password then log the user in
			logIn();
		} else {
			logOut();
		}
	} else {
		logOut();
	}
}
//we use nonces to prevent back button/refresh resubmission of credentials
function checkNonce(){
	if (!isset($_SESSION['nonce'])){
		return false;
	}
	if (!isset($_POST['nonce'])){
		return false;
	}
	if ($_SESSION['nonce'] !== $_POST['nonce']){
		return false;
	} else {
		unset($_SESSION['nonce']);
		return true;
	}
}
function getNonce(){
	if (isset($_SESSION['nonce'])){
		
	} else {
		$_SESSION['nonce'] = md5(uniqid(rand(), true));
	}
	return $_SESSION['nonce'];
}
function logIn(){
	$_SESSION['username'] = $_POST['loginpass'];
	//for debuggin
	echo <<<HTML
logged in.  Click <a href="{$_SERVER['PHP_SELF']}?logout">here</a> to logout
HTML;
}

function isLoggedIn(){
	if (isset($_SESSION['username'])){
		if (!isTimedOut()){
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function isTimedOut(){
	if (empty($_SESSION['lastaccess'])){
		return true;
	}
	if ((time() - TIMEOUT) <= $_SESSION['lastaccess']){
		return true;
	} else {
		$_SESSION['lastaccess'] = time();
		return false;
	}
}

function checkPassword($pwd){
	if (!checkNonce()) return false;
	$pwd = trim ($pwd);
	return ($pwd === 'password');
}

function logOut($redirect = false){
	unset($_SESSION['username']);
	unset ($_SESSION['lastaccess']);
	if ($redirect){
		header('Location:'.$_SERVER['PHP_SELF']);
		exit();
	} else {
		displayLoginForm();
	}
}

function displayLoginForm(){
	$nonce = getNonce();
	$form = <<<HTML

<div id="message">
You are not authenticated.  Please login.
</div>
<div id="form">
<form method="post" action="{$_SERVER['PHP_SELF']}">
<fieldset>
<legend>Login Here</legend>
<input type="text" name="loginpass"/> &nbsp; Enter your password<br/>
<input type="submit" name="submit" value="login"/>
<input type="hidden" name="nonce" value="$nonce"/>
</fiedset>
</form>
</div>
HTML;
	echo $form;
	die();
}
?>
 
Thank you for the comprehensive reply jpadie, I will definately digest each area of the code to work out what does what, especially the nonces part which I had never heard of before.

I am enjoying this project that was thrust upon me, I might even try to build a website of my own after this :)
 
nonce is a term i borrowed from wordpress. i think it has a meaning ('number used once').

the wordpress implementation is similar to the method i have used for a few years (as per above) to prevent form resubmission from causing data conflicts (and security breaches).
 
I can`t get the code to work, it keeps logging out after every page, and a page such as edit.php?id=2 will not display as it goes to login then to edit.php each time :eek:(
 
have you changed the timeout to a non-debug level? it's currently set at 60 seconds.
 
Yes I changed it to 600 however if I click a link, type in password, then click another link straight away I need to type password, click another link, type password etc

The edit.php?id=2 just does not work, after logging in it sends me to edit.asp
 
you probably have something wrong with your sessions then. run phpinfo() to establish where your session data is being saved and then check that the relevant directory has read/write permissions for the php process.

you can debug by dumping the superglobals to the screen at each point.
 
Thanks for helping me with this, especially on the weekend :)

It seems it is being saved to the /tmp directory, I looked on ftp and couldn`t find any folders with that name, so created one but still no luck.

session
Session Support enabled
Registered save handlers files user

Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 On On
session.bug_compat_warn On On
session.cache_expire 180 180
session.cache_limiter nocache nocache
session.cookie_domain no value no value
session.cookie_lifetime 0 0
session.cookie_path / /
session.cookie_secure Off Off
session.entropy_file no value no value
session.entropy_length 0 0
session.gc_divisor 100 100
session.gc_maxlifetime 1440 1440
session.gc_probability 1 1
session.name PHPSESSID PHPSESSID
session.referer_check no value no value
session.save_handler files files
session.save_path /tmp /tmp
session.serialize_handler php php
session.use_cookies On On
session.use_only_cookies Off Off
session.use_trans_sid Off Off
 
sure

Code:
<?php
require_once 'login.php';
?>
<!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] xml:lang="en" lang="en">
<head>
<title>Edit</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="../stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body> 
<div class="container"> 
  <div class="header"> </div> 
  <div class="main_area"> 
    
<h1>Administration area</h1>
				
<?
//no id value so come to list page
if (!isset($_GET["id"])) {
require "../dbconn.php";
$query  = "SELECT * FROM properties";
$result = mysql_query($query) or die (mysql_error());

//display list
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				if($style=='search_result_even'){$style='search_result_odd';}
    else{$style='search_result_even';}
    echo "<div class='$style'>{$row['name']}, {$row['address']} - <strong>&pound;{$row['price']}</strong></span>" .
         "<p class='MainText'>{$row['maindesc']} <span class='BlueText'>Property ID {$row['id']}.</span></p>" .
         "<p class='MainText'><a href='edit.php?id={$row['id']}' class='BlueText'>Edit property</a></p>" .
									"</div>";}

} else {

require "../dbconn.php";
$query1=" SELECT * FROM properties where id = '{$_GET['id']}' ";
$result1=mysql_query($query1);
$rs = mysql_fetch_array($result1, MYSQL_ASSOC);




echo "<form action='post' action='editscript.php'>" .
     "<input type='hidden' name='id' value='{$rs['id']}'>" .
					"Property name: <input type='text' name='name' value='{$rs['name']}'>" .
					"<br />Property address: <input type='text' name='address' value='{$rs['address']}'>" .
					"<br />Property city: <input type='text' name='city' value='{$rs['city']}'>" .
					"<br />Property price: <input type='text' name='price' value='{$rs['price']}'>" .
					"<br />Property description: <textarea name='maindesc'>{$rs['maindesc']}</textarea>" .
					"<br />Property key features: <textarea name='keyfeatures'>{$rs['keyfeatures']}</textarea>" .
					"<br />Property living room: <textarea name='livingroom'>{$rs['livingroom']}</textarea>" .
					"<br />Property kitchen: <textarea name='kitchen'>{$rs['kitchen']}</textarea>" .
					"<br />Property bedroom number: <input type='text' name='bedrooms' value='{$rs['bedrooms']}'>" .
					"<br />Property bedroom 1: <textarea name='bedroom1'>{$rs['bedroom1']}</textarea>" .
					"<br />Property bedroom 2: <textarea name='bedroom2'>{$rs['bedroom2']}</textarea>" .
					"<br />Property bedroom 3: <textarea name='bedroom3'>{$rs['bedroom3']}</textarea>" .
					"<br />Property bedroom 4: <textarea name='bedroom4'>{$rs['bedroom4']}</textarea>" .
					"<br />Property bathroom: <textarea name='bathroom'>{$rs['bathroom']}</textarea>" .
					"<br />Property balcony: <textarea name='balcony'>{$rs['balcony']}</textarea>" .
					"<br />Property property type: <input type='text' name='propertytype' value='{$rs['propertytype']}'>" ;



//close else of main if
}
?>
				

  </div> 
 
</div> 
</body>
</html>
 
I have looked at this a million times and can`t find the fault!
 
my fault. i should have debugged it more before publishing.

change this line

Code:
if ((time() - TIMEOUT) <= $_SESSION['lastaccess']){

to

Code:
if ((time() - TIMEOUT) [red]>[/red]= $_SESSION['lastaccess']){
 
yet again, my apologies. i had made a further change during debugging that i forgot to report.

please add this as the first line of the logIn() function
Code:
$_SESSION['lastaccess'] = time(); //sets the timer
 
yay that works thanks. If you are ever in Derbyshire I'll get you a drink or 10 :eek:)
 
aha! my kind of payment!

i've written better login scripts and classes, that are more granular and interface to databases and/or flat files. Also contain password reminder, remember me scripts etc. if you want anything more like this for your application let me know and i'll dust one off for publication.
 
I have really enjoyed doing this despite constantly being baffled by it. I may take you up on that offer jpadie just as soon as I have fully digested what is going on in this script and read a few more tutorials (and w3schools). I am definately going to have a go at setting up a website of my own.
 
if you do [set up a website] take a look at bluehost. i've just signed up with them and rate both their pricing and customer support!


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top