note 71693 rejected from function.setcookie by bjori
| From: | bjori@php.net | Date: | Tue, 12 Dec 2006 09:03:56 +0000 |
| Subject: | note 71693 rejected from function.setcookie by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-120542@lists.php.net to get a copy of this message | ||
Note Submitter: hakimu at gmail dot com
----
It's cumbersome to always keep entering your username and password during login. More it
reduces the hit rate as well. Using the "Remember me on this computer" option during login
may help many users, even thought it's a security risk.
Example code of the Login Form
<?php
echo "<form name='frmlogin' method='post'
action='./login.php'>";
echo "User ID: <input type='inputbox' name='txtuser'>";
echo "Password : <input type='inputbox' name='txtpasswd'>";
echo "<input type='checkbox' name='chkrem_me' value='TRUE'>
Remember me";
echo "<input type='submit' name='Submit'
value='Login'>";
?>
Example code of the login.php file
<?php
// Get values form the frmlogin
// htmlspecialchars() used to strip malicious code
$userid = htmlspecialchars($_REQUEST['txtuser'], ENT_QUOTES);
$pass = md5(htmlspecialchars($_REQUEST['txtpasswd'], ENT_QUOTES));
$remme = $_REQUEST['chkrem_me'];
// redirect urls for login ok and login fail
$loginok_url = "./mamber.php";
$loginfail_url = "./loginfail.php";
// SQL query string for authentication with database
$sqlstr = "SELECT COUNT(*) FROM tbl_user WHERE userid = '$userid' AND password =
'$pass';";
// Connect to database
$mysqldb = mysql_connect("localhost","user_name","password") or
die("Unable to connect to database server");
// Select database
$selected = mysql_select_db("datbase_name",$mysqldb) or die ("Unable to select
database");
// Execute query
$valid = mysql_query($sqlstr,$mysqldb);
// If user exists with valid password
if ($valid > 0)
{
// if remember me ticked
if($remme)
{
// cookie login valid for 30 days, accessible to entire directory structure and valid for
all subdomains of example.com
setcookie('login',TRUE,time()+3600*24*30,'/','.example.com',0);
}
// if remember me NOT ticked
// cookie is set until the Browser close
// time can be set to both "NULL" and "false"
// If you want to specify a time e.g like 1 hour then "time() + 3600"
else
{
setcookie('login',TRUE,NULL,'/','.example.com',0);
}
// Redirect to Member page
header("Location: " . $loginok_url);
}
// if invalid user name or password
else
{
header("Location: " . $loginfail_url);
}
// close database
mysql_close($mysqldb);
?>