php script- Allow one session only at a time - php

Please help me to validate one session only at a time, kindly see the below script which currently allows the same username to login any number of sessions.
I am not sure when and where to validate the session, help me in adding only those few lines which can validate the session for a username.
<?php // accesscontrol.php
include_once 'common.php';
include_once 'db.php';
session_start();
$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];
if(!isset($uid)) {
?>
<!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>
<title>Login</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<head>
<style type="text/css">
<!--
.style1 {
font-size: 16px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.style3 {
font-size: 12px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
body {
background-color: #D7F0FF;
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
-->
</style>
</head>
<body>
<h1 class="style1"> <br><br>Amogh Site - Login Required </h1>
<span class="style3"><br>
You <strong>must login to access this area </strong>of the site. <br>
<br>
If you are not a registered user, please contact your Admin
to sign up for instant access!</span>
<p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<span class="style3">User ID:
<input type="text" name="uid" size="12" />
<br>
<br />
Password:</span>
<input type="password" name="pwd" SIZE="12" />
<br>
<br />
<input type="submit" value="Login" />
</form></p>
</body>
</html>
<?php
exit;
}
$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;
dbConnect("hitek_svga3");
$sql = "SELECT * FROM user WHERE
userid = '$uid' AND password = '$pwd'";
$result = mysql_query($sql);
if (!$result) {
error('A database error occurred while checking your '.
'login details.\\nIf this error persists, please '.
'contact you#example.com.');
}
if (mysql_num_rows($result) == 0) {
unset($_SESSION['uid']);
unset($_SESSION['pwd']);
?>
<!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>
<title> Access Denied </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<style type="text/css">
<!--
.style1 {
font-size: 16px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.style3 {
font-size: 12px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
-->
</style>
</head>
<body>
<br/>
<br/>
<h1 class="style1"> Access Denied </h1>
<p class="style3">Your user ID or password is incorrect, or you are not a
registered user on this site. To try logging in again, click
here. To access, please contact our Admin !</a>.</p>
</body>
</html>
<?php
exit;
}
$username = mysql_result($result,0,'fullname');
$_SESSION['user'] = mysql_result($result,0,'userid');
$_SESSION['email'] = mysql_result($result,0,'email');
$_SESSION['notes'] = mysql_result($result,0,'notes');
?>

Firstly, why are you storing passwords in session variables?
Secondly, your code assumes that the session variables 'uid' and 'pwd' will exist if the POST vars 'uid' and 'pwd' don't, so you'll need to make sure that either or exist before you allow your script to continue. This will have to be done AFTER the session_start() function:
<?php // accesscontrol.php
include_once 'common.php';
include_once 'db.php';
session_start();
if(
(!isset($_SESSION['uid']) || !isset($_SESSION['pwd'])) &&
(!isset($_POST['uid']) || !isset($_POST['pwd']))
{
//Redirect or throw exception or whatever
}
$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];

You should not:
Keep cleartext password in the database
Using mysql extension
Develop in 2012 without a framework
The point of the question is: how does PHP tell which user a request comes from? Last time I checked it used a token sent as a GET parameter or with a cookie in the HTTP request header section (I think it was called PHPSESSID).
Obviously to guarantee that nobody steals sessions, identity token must be exchanged over a secure channel, ie once the user logs in you have to generate a session id and disable plain HTTP sockets on port 80. The scripts that need a logged user must be kept in a separate host which only allows HTTPS on port 443.
The session ID will be assigned from the login script and will be kept in a column in the user table. BTW, regular applications use a separate table to associate sessions to user, but since you require one client per user a column in the user table is enough.
So when a request comes with a session token, your authorization logic will check in the user table if the token is still valid. It should use the token to authenticate the user, so if the request doesn't contain one or the token is not found in the database, you issue a 403 FORBIDDEN and suggest the login URL in the Location header - you can also write a HTML page with an <a> link in the case the agent doesn't automatically follows the redirect.
The login script is committed to update the column with the token, depending on what you want to do: invalidate the old session or prevent the creation of new ones until the user explicitely logs out on the other client (the latter causes troubles in the case the user can't access the old machine where he previously logged in from, maybe because if powered off the mobile device or because it was in a different building)

Related

how to differentiate between different inputs in the same html form using php

I'm building a chatbot in php I want the functionality of that chatbot to be that it is used for resetting the password, so it asks for employee's PIS_CODE which it uses as a primary key to change the password in the password column, you can see my database table.
see it has columns PIS_CODE and password, so I ask the user for PIS_CODE and then it asks the user for the new password and then it changes the password in the corresponding column
so I've been able to take the PIS_CODE and use it as a primary key to reset the password but the password which is reset is the PIS_CODE itself
see here I wanted to reset the password for 41000000 PIS_CODE but it reset the password to 41000000 itself. So it seems like my chatbot assumes the input value to be the pis code and it updates the password column with that value only, so my chatbot is not able to differentiate between different inputs. Plus I want to use only a single form and a single input field.
you can see my chatbot here.
HTML Code :
<div class="form-group">
<form action="process.php" id="form" name="f2" method="POST" >
<input type="textarea" id="tt" name="input" placeholder="Type Your Message" style="position:absolute; bottom:0; height:30px; width:100%; height:50px;" required />
</div>
// this is the code which takes the input for the PIS_CODE
$msgg=$_POST['input'];
// this is the code which takes the input for the password
$pass=$_POST['input'];
// the problem is it saves the same input(that is PIS_CODE) in both the variables($msgg and $pass)
FULL Code:
<?php
require_once("config.php");
$msgg=$_POST['input'];
$msg=strtolower($msgg);
$ID = $msg;
$length=strlen($msg);
$flag=0;
$pass=$_POST['input'];
$update = "UPDATE lala SET password='$pass' WHERE PIS_CODE=".$msg;
$res_4=mysqli_query($con,$update);
$sql1 = "SELECT * FROM lala WHERE PIS_CODE='$msg'";
$res_u = mysqli_query($con, $sql1);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
.in
{
background-color:rgb(64,128,255);
color:white;
padding:10px;
right:0;
width:130px;
text-align: center;
height:auto;
border-radius: 5px;
margin-left: 120px;
margin-bottom: 5px;
}
.out
{
background-color:rgb(241,240,240);
color:black;
padding:10px;
left:5;
width:130px;
text-align: center;
height:auto;
border-radius: 15px;
}
</style>
<body>
<div class="in">
<?php echo "$msgg"; ?>
</div><br>
<div class="out">
<?php
if (($_POST['input']) =='password reset')
{
echo "Do you want to reset your password? ";
}
else if (($_POST['input']) =='yes')
{
echo "Sure, Please provide PIS code ";
}
if (mysqli_num_rows($res_u) == 1)
{
echo 'Pis verified';
echo "Enter new password";
}
if($update){//if the update worked
echo "Update successful!";
}
?>
</div><br>
</body>
</html>
You could use PHP session. This would do what you want:
require_once("config.php");
$msgg=$_POST['input'];
$msg=strtolower($msgg);
$ID = $msg;
$length=strlen($msg);
$flag=0;
session_start();
if(isset($_SESSION['PIS_CODE'])){
$pass=$_POST['input'];
$update = "UPDATE lala SET password='$pass' WHERE PIS_CODE=".$_SESSION['PIS_CODE'];
$res_4=mysqli_query($con,$update);
unset($_SESSION['PIS_CODE']);
}
else{
$sql1 = "SELECT * FROM lala WHERE PIS_CODE='$msg'";
$res_u = mysqli_query($con, $sql1);
if (mysqli_num_rows($res_u) == 1) {
$_SESSION['PIS_CODE'] = $msg;
}
}
If i were you (i.e. working on a chatbot), i'd use the $_SESSION object for more than that. You could keep your simple 1 input form, and use PHP session to keep information about the next expected answer, or for a serie of questions like in your example, to know what is the current question, an many other possible usage.

Can't get login page to redirect when user credentials are entered

I'm having so problem with a little project I've been working on. I'm trying to learn as much as I can about html, php, MySQL, etc. I created a database with MySQL and I know that I have that setup correctly, because the login page I'm using is able to know what is the right, and wrong user accounts. I cant seem to be able to get the page to redirect to the welcome page on a successful login. Here is my code.
Login Page Code
<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_register("myusername");
$_SESSION['username'] = $myusername;
header("location: welcome.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login Page</title>
<style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style>
</head>
<body bgcolor = "#FFFFFF">
<div align = "center">
<div style = "width:300px; border: solid 1px #333333; " align = "left">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style = "margin:30px">
<form action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
Session Code
<?php
include('config.php');
session_start();
$user_check = $_SESSION['myusername'];
$ses_sql = mysqli_query($db,"select username from admin where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
if(!isset($_SESSION['username'])){
header("location:welcome.php");
}
?>
Redirected Page
<?php
include('session.php');
?>
<html>
<head>
<title>Welcome </title>
</head>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
<h2>Sign Out</h2>
</body>
</html>
<?php
session_start();
if(session_destroy()) {
header("Location: login.php");
}
strong text ?>
<?php
session_start();
include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT id FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['username'] = $myusername;
header("Location: welcome.php");
}else {
$error = "Your Login Name or Password is invalid";
header("Location: login.php?error=".$error);
}
}
else {
if (isset($_GET['error'])) {
echo $_GET['error'];
}
?>
<html>
<head>
<title>Login Page</title>
<style type="text/css">
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
}
label {
font-weight: bold;
width: 100px;
font-size: 14px;
}
.box {
border: #666666 solid 1px;
}
</style>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<div style="width:300px; border: solid 1px #333333; " align="left">
<div style="background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style="margin:30px">
<form action="" method="post">
<label>UserName :</label><input type="text" name="username" class="box"/><br/><br/>
<label>Password :</label><input type="password" name="password" class="box"/><br/><br/>
<input type="submit" value=" Submit "/><br/>
</form>
<div style="font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
<?php
}
?>
this is Session Code
<?php
session_start();
include('config.php');
$user_check = $_SESSION['myusername'];
$ses_sql = mysqli_query($db,"select username from admin where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
?>
Redirected Page
<?php
include('session.php');
?>
<html>
<head>
<title>Welcome </title>
</head>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
<h2>Sign Out</h2>
</body>
</html>
<?php
session_start();
if(session_destroy()) {
header("Location: login.php");
}
?>
Oh... you can't set headers after some html elements. If you want to redirect with php, you have to basically set it before anything loads. You can still simply redirect using some javascript tho...
<script>window.location="index.html";</script>
that makes you go back to index just when you let it run.
I hope I helped. I'm 19, and at same tracks as you bud! have fun!
Try it, I think this is useful for you,
header('Location: http://www.example.com/welcome.php');
and try to change location of session_start(); top of the config.
There can be a number of reasons. The most probable one is that the script doesn't exit after issuing the header. Note, that header() merely adds a header to the page, but doesn't stop further execution. So the login page recognizes your login, issues the redirect header, but the execution continues and the login form is rendered again, which stops redirect.
Suggested: put exit; after the header() call.
Another possible reason there's something output before the header goes out. I.e. if you accidentally produce any text and then call header(...) - the the header won't do anything. This issue can be detected by PHP, you should receive a warning in such a case. Make sure, that you have enabled errors and warnings - check that error_reporting is set to E_ALL and display_errors is turned on in your ini file. This will help you see a lot of issues, while developing.
You would also benefit from a couple of debugging tools to understand what goes wrong in this case. In the order by easiness to use immediately:
Browser dev tools. Right click on the page in your browser, select Inspect. It will open you the browser development tools. In particular you're interested in Network requests tab. Switch to it and then re-submit the login form. You will see the request in the tab. Examine it: was the header present there? Was the method POST as you intended? What was the response body?
Debugging proxy. E.g. Fiddler for Windows, Charles for OSX.
This is a software, that helps you see all the requests made by your browser. If your workflow has multiple redirects, then browser's Network tab won't show you anything except the last request. While proxy will store all the urls and let you examine how the case evolved.
PHP Debugger - install and activate Xdebug, setup your IDE (do you use one?) to use that. It will help you step through the PHP code and see whether the algorithm indeed worked right.

How can I display userID in Sessions?

I would like to get except of the username and user ID in a page. About that I created two php pages. Also my database consists of 3 columns userid, username, password. The login.php page is
<?php
session_start();
//#$userid = $_GET['userid'];
#$username = $_POST['username'];
#$password = $_POST['pass'];
if(#$_POST['Submit']){
if($username&&$password)
{
$connect = mysql_connect("localhost","*****","") or die("Cannot Connect");
mysql_select_db("project") or die("Cannot find the database");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
//$query = mysql_query("SELECT * FROM users WHERE userid='$userid' and username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while ($row = mysql_fetch_assoc($query))
//while ($row = mysql_fetch_array($query))
{
$dbuserid = $row['userid'];
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername&&$password==$dbpassword)
{
echo "You are login!!!!! Continue now with the survey <a href='mainpage.php'>here</a>";
$_SESSION['username']=$username;
$_SESSION['userid']=$userid;
}
else
{
echo "<b>Incorrect Password!!!!</b>";
}
}
else
//die("That user does not exist");
echo "<b>That user does not exist</b>";
}
else
echo "<b>You must enter a username and a password</b>";
}
?>
<!--<!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=iso-8859-1" />-->
<title>Login Page</title>
<style type="text/css">
h2 {letter-spacing: 10px; font-size: .2in; background-color: #33CC00; color: #000000; text-transform:uppercase; width:260px}
span {color: #FF00CC}
legend {font-variant: small-caps; font-weight: bold}
fieldset {width: 260px; height: 100px; font-family: "Times New Roman", Times, serif; background-color: #CCCCCC; color: #000000}
label {display:block;}
.placeButtons {position: relative; left: 0px; width: 70px; margin: 5px; 0px;}
</style>
</head>
<body background="images/good.jpg">
<h2>Login Page</h2>
<form name="loginform" method='POST'>
<fieldset>
<legend>Form</legend>
<label>Username: <input type="text" name="username"/><span>*</span></label><br/>
<label>Password: <input type="password" name="pass"/><span>*</span></label>
<input class="placeButtons" type="reset" value='Reset'/>
<input class="placeButtons" type="submit" name="Submit" value='Login'/>
<a href='registration.php'>Register</a>
</fieldset><br>
<a href='firstpage.php'><-- Go Back</a>
</form>
</body>
</html>
and the page which is a welcome page of the user
<?php
session_start();
if ($_SESSION['username'])
{
//echo "Welcome, ".$_SESSION['username']."! <a href='logout.php'>Logout</a>";
echo "Welcome, ".$_SESSION['username']."<br>".$_SESSION['userid']. "<a href='logout.php'>Logout</a>";
}
else
die("You must be logged in!!");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />-->
<title></title>
</head>
<body background="images/good.jpg">
</body>
</html>
The problem is that in the welcome page it shows me only the username and not the UserID. What am I missing? Furthermore, I know that my login page is not the best and is a typical example of SQL injection attack. I have to improve it.
A quick thing i noticed. That might be the problem. The $_SESSION['userid'] is getting value from $userid which is not set. Also using # to supress your error is not a good practice. use isset to check if the variable is set and continue.
$_SESSION['userid'] = $userid; //where are you getting $userid from?
This should be
$_SESSION['userid'] = $dbuserid;
Also instead of using statement like
if ($_SESSION['username'])
First check if the variable is set like this
if ( isset($_SESSION['username']) ){
//now continue your work
}
and make sure you use ini_set('session_save_path', 'new_dir') or the function session_save_path when you are on a shared webhost. sessions that are in the same directory from different websites are prone to session stealing / snooping / modification.
I checked the PHP source code PHP doesn't keep track which session id's are made by with website (HOST) that why this attack works if the attacker has a account on the same webhosting
So never put to much trust in the SESSION array because you think it's safe because it's server generated
it's not if you don't make countermeasures...

How to delete entire site directory if login attempts reach maximum

I have a very confidential site where only a few people have access to logging in. How do I check if a user has attempted to login in three times and if they have, the entire directory is deleted from my server. Is this difficult to do?
Here is my login page:
<?php
require_once('scripts/user_authentication.php');
?>
<!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>
<link href='http://fonts.googleapis.com/css?family=Inder' rel='stylesheet' type='text/css'>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Access login</title>
<link href="../styles/users.css" rel="stylesheet" type="text/css" />
<style>
span {font-family: 'Inder', sans-serif; color: #369; font-style: italic;}
#login {width: 400px; margin: 60px auto 0 auto; padding: 20px; text-align: center;
box-shadow: 0px 9px 21px rgba(0, 0, 0, 0.63);
-moz-box-shadow: 0px 9px 21px rgba(0, 0, 0, 0.63);
-webkit-box-shadow: 0px 9px 21px rgba(0, 0, 0, 0.63);
}
#login p {text-align: left;}
form {padding: 0; margin: 0; }
input {margin: 0; padding: 0;}
h1 { margin: 0 0 20px 0; padding: 0;}
</style>
</head>
<body>
<div id="login">
<h1><span>p*******</span> Partners Only</h1>
<div id="inner">
<?php if ($failed) { ?>
<p class="warning">Login failed. Try Again. Please contact ******* ***** if you do not know your access information. After multiple attempts this site will self destruct. Thank you for your cooperation.</p>
<?php } ?>
<form id="form1" name="form1" method="POST">
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="signin" id="signin" value="Sign in" />
</p>
</form>
</div>
</div>
</body>
</html>
and here is user_authentication:
<?php
$failed = FALSE;
if ($_POST) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$failed = TRUE;
} else {
require_once('library.php');
// check the user's credentials
try {
$auth = Zend_Auth::getInstance();
$adapter = new Zend_Auth_Adapter_DbTable($dbRead, 'users', 'first_name', 'family_name', 'password' 'sha1(?)');
$adapter->setIdentity($_POST['username']);
$adapter->setCredential($_POST['password']);
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$storage = $auth->getStorage();
$storage->write($adapter->getResultRowObject(array(
'username', 'first_name', 'family_name')));
header('Location: members_only.php');
exit;
} else {
$failed = TRUE;
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
if (isset($_GET['logout'])) {
require_once('library.php');
try {
$auth = Zend_Auth::getInstance();
$auth->clearIdentity();
} catch (Exception $e) {
echo $e->getMessage();
}
}
Your approach (deleting files for the user) is really bad practice, but if you absolutely need to do it, here is one way...
Create a database table (or entries in an existing table) to store the username and number of attempts. Before authenticating, check the attempts are below a set amount. In the authentication part, if the password is wrong, increment the "attempts" column. Whenever the user successfully logs in, set attempts to zero again. If they exceed the number of attempts, delete the files or take whatever security measures you need to.
Now, to make this design better, I would suggest not to actually delete the data on the server. Instead, I would recommend that after X number of failed attempts, increased security measures are applied to people attempting to log in for that username, such as;
require the user to solve a captcha so you know they aren't a bot trying multiple passwords
store "security questions" for each user (e.g. "What is your birthday"), and require them to answer those
lock the account out and have a secure procedure for the real user to gain access again
As people mentioned in the comments it is very dangerous doing that.
However, if you still believe that the information is of that importance and the link to the login page is very secret and you have backups somewhere else, this code should do it:
<?php
session_start(); // Add this only if you don't have it in some other header files
// Checking if the session variable exists and initiating it if it does not.
if (!isset($_SESSION['failed'])) {
$_SESSION['failed'] = 0;
}
$failed = FALSE;
if ($_POST) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$failed = TRUE;
} else {
require_once('library.php');
// check the user's credentials
try {
$auth = Zend_Auth::getInstance();
$adapter = new Zend_Auth_Adapter_DbTable($dbRead, 'users', 'first_name', 'family_name', 'password' 'sha1(?)');
$adapter->setIdentity($_POST['username']);
$adapter->setCredential($_POST['password']);
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
// Setting the counter to 0 in case of successful login.
$_SESSION['failed'] = 0;
$storage = $auth->getStorage();
$storage->write($adapter->getResultRowObject(array(
'username', 'first_name', 'family_name')));
header('Location: members_only.php');
exit;
} else {
$failed = TRUE;
// Increment the failed logins counter at each failed login.
$_SESSION['failed']++;
// In case of 3 or more failed attempts
if ($_SESSION['failed'] > 3) {
// Remove some directory
rmdir("/path/to/the/dir");
$_SESSION['failed'] = 0;
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
if (isset($_GET['logout'])) {
require_once('library.php');
try {
$auth = Zend_Auth::getInstance();
$auth->clearIdentity();
} catch (Exception $e) {
echo $e->getMessage();
}
}

View and change sessions variables in a browser

Debugging a PHP program, is there any add-on/plug-in for browser which I can view sessions variables (those PHP $_SESSION["foobar"] )?
Best if I can change the value in the variables.
There is no way to manipulate the values stored in sessions from the client side.
That's one of the main reasons you'd use a session over a cookie - YOU control the data.
With cookies, the user can manipulate the data.
The only way to access/manipulate session data from the client side would be with an Ajax call or other JavaScript mechanism to call another php script, which would be doing the retrieval/manipulation of the session data via the session_ functions.
$_SESSION is a server-side array of variables. If we could read or change the values, there are many things that we could do to hack or cause other bad things to happen.
However, using phpinfo(); we can view session variables - but we cannot change the value.
Even better, we can debug all session variables with
print_r($_SESSION);
//if you echo "<pre>" before, and a closing "</pre>" after, it prints very cleanly.
some other useful commands:
session_start(); // start session -- returns Session ID
session_destroy(); // unset all session variable
Session is an array so if you set $_SESSION['key']='value'; it is same like $array['key']=value; - only, what is special about $_SESSION - is that it persists until the window is closed, or session_destroy() is called.
You can use this code below:
<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
$session = eval("return {$_POST['session']};");
if (is_array($session)) {
$_SESSION = $session;
header("Location: {$_SERVER['PHP_SELF']}?saved");
}
else {
header("Location: {$_SERVER['PHP_SELF']}?error");
}
}
$session = htmlentities(var_export($_SESSION, true));
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Session Variable Management</title>
<style>
textarea { font: 12px Consolas, Monaco, monospace; padding: 2px; border: 1px solid #444444; width: 99%; }
.saved, .error { border: 1px solid #509151; background: #DDF0DD; padding: 2px; }
.error { border-color: #915050; background: #F0DDDD; }
</style>
</head>
<body>
<h1>Session Variable Management</h1>
<?php if (isset($_GET['saved'])) { ?>
<p class="saved">The session was saved successfully.</p>
<?php } else if (isset($_GET['error'])) { ?>
<p class="error">The session variable did not parse correctly.</p>
<?php } ?>
<form method="post">
<textarea name="session" rows="<?php echo count(preg_split("/\n|\r/", $session)); ?>"><?php echo $session; ?></textarea>
<input type="submit" value="Update Session">
</form>
</body>
</html>
Be aware however that while the session 'variables' are stored server-side, the Session ID is either in the GET/POST URL (a VERY BAD idea) or stored in a browser cookie, (better security), but still susceptible to manipulation/attack/etc if you don't hand Cookie based session IDs carefully.
http://en.wikipedia.org/wiki/Session_fixation
http://en.wikibooks.org/wiki/PHP_Programming/sessions#Avoiding_Session_Fixation

Categories