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...
Related
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.
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.
Firstly I must excuse for my bad English. I need help with my code to login.php because I´m doing a permission system trough sessions but this session called "$_SESSION['perms']" does not accepts database values. I´m searching couple of weeks to find an answer but unsuccessfully. And so I´m appeal here.
this is code of my login:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title></title>
<style>
.odstavec {
margin-top: 0px;
margin-bottom: 0px;
}
</style>
<?php
$dbc = mysqli_connect('localhost','root','root') or
die('could not connect: '. mysqli_connect_error());
mysqli_select_db($dbc, 'loginsystem') or die('no db connection');
session_start();
if(isset($_POST['go'])){
$usr = mysqli_real_escape_string($dbc, htmlentities($_POST['u_name']));
$psw = ($_POST['u_pass']);
$q = "SELECT * FROM members WHERE username='$usr' AND password='$psw' ";
$res = mysqli_query($dbc, $q);
if(mysqli_num_rows($res) == 1){
$_SESSION['log'] = 'in';
$_SESSION['username'] = $_POST['u_name'];
$_SESSION['perms'] = "SELECT $usr FROM members WHERE perms='".$_SESSION['perms']."'";
header('location:novinky.php');
}
elseif(!$_POST['u_name'] || !$_POST['u_pass']){
$error = 'Všechna pole musí být vyplněná!';
}else{ //create an error message
$error = 'Chybné jméno nebo heslo. Prosím zkuste to znovu';
}
} //end of isset go
?>
</head>
<body>
<form method="post" action="#">
<p class="odstavec"><label for="u_name">Uživatlské jméno:</label></p>
<p class="odstavec"><input type="text" name="u_name" value=""></p>
<p class="odstavec"><label for="u_pass">Heslo:</label></p>
<p class="odstavec"><input type="password" name="u_pass" value=""></p>
<p><button type="submit" name="go">Přihlásit</button></p>
</form>
<!-- A paragraph to display eventual errors -->
I am tried many of ways. But nothing work. Also there is my administration.php may be an error in it but I watched in this an progress.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>Administrace</title>
</head>
<?php
session_start();
if (isset($_SESSION['log']) && ($_SESSION['perms']=="3")){
echo '<body>';
echo '<div class="up_div">';
echo '<img style="position: absolute; top: 0px; left: 0px" src="../images/admin_up_div.png">';
echo '<p style="position: absolute; top: 0px; left: 0px">Vítej '.$_SESSION["username"].'</p>';
echo '</div>';
echo '</body>';
}
elseif (isset($_SESSION['log']) && ($_SESSION['perms']=="1")){
echo 'Omlouvám se, ale pro tuto sekci nemáte dostatečná oprávnění'; //Sorry message if they haven´t permissons
header('location: novinky.php');
}else{
header('location: login.php');
}
?>
</html>
Beforehand I´m thanks for answers.
Is the correct information in the database? To make sure change...
$res = mysqli_query($dbc, $q);
to
echo $usr."<br/>";
echo $psw."<br/>";
echo $q;
exit();
$res = mysqli_query($dbc, $q);
What I think is happening is that your mysqli_real_escape_string and htmlentities is changing the user string so it no longer matches.
If its not obvious try running $q in the command line or phpmyadmin and see if any errors popup.
Also like orique said, you need to sanitize your password.
I just started a project with a new client and have run into an issue that I haven't had before.
I've moved a copy of their site to my local machine (running the latest version of mamp) and I got their database set up with no issue.
The main pages load fine, but after I log in and am taken to the admin dashboard (a custom cms), clicking on any link causes the page to hang and timeout.
I've narrowed the issue down to the initial call to session_start() on the subpages and removing it and any code that references the session data allows the pages to load.
The site did not have a php.ini file.
I've googled around and found several suggestions of using session_write_close() at the end of each file, and before redirection. I've tried this and still get the timeout.
I've noticed that when I log in the session is created without issue in the mamp/tmp/php folder on my mac, and the dashboard page that loads can be refreshed (calling session_start() again) without the page timing out.
Also, once I try to load any other page in the admin (causing the timeout) I can no longer access the dashboard page because it begins to timeout to. I then have to delete the session file to regain access to any pages that start a session.
Here is the dashboard page code, I don't see anything in there that should cause the next page to load to have a session issue (I'm not looking for best-practices suggestions, I literally just inherited this codebase).
<?php
session_start();
if(basename($_SERVER['PHP_SELF'])!="index.php") {
if(!isset($_SESSION['is_logged_in'])) {
header("Location:index.php");
die();
}
}
?>
<!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" xml:lang="en" lang="en">
<head>
<title>RVC Admin: Dashboard</title>
<?php
include "includes/connect.php";
include "includes/headers.php";
?>
</head>
<body>
<div id='main'>
<?php
include "includes/menu.php";
?>
<h1>RVC Admin System</h1>
<?php
$result = mysql_query("SELECT COUNT(ID) as HOWMANY FROM listings");
if(#mysql_num_rows($result)>0) {
$row = mysql_fetch_assoc($result);
$LISTINGS = number_format($row['HOWMANY']);
}
$result = mysql_query("SELECT COUNT(id) as HOWMANY FROM user");
if(#mysql_num_rows($result)>0) {
$row = mysql_fetch_assoc($result);
$ADMINS = number_format($row['HOWMANY']);
}
print "<p>There are ".$LISTINGS." listings in the system, and ".$ADMINS." admins.</p>";
$result = mysql_query("SELECT description FROM LGBTlevel ORDER BY description");
if(#mysql_num_rows($result)>0) {
print "<div style='float: left; padding-right: 30px;'><p>Levels:</p>";
print "<ul style='margin: 2px 0 5px 18px; padding: 0;'>";
while($row = mysql_fetch_row($result)) {
print "<li style='margin-bottom: 2px;'>".$row[0]."</li>";
}
print "</ul></div>";
}
$result = mysql_query("SELECT description FROM LGBTtype ORDER BY description");
if(#mysql_num_rows($result)>0) {
print "<div style='float: left; padding-right: 30px;'><p>Types of Listings:</p>";
print "<ul style='margin: 2px 0 5px 18px; padding: 0;'>";
while($row = mysql_fetch_row($result)) {
print "<li style='margin-bottom: 2px;'>".$row[0]."</li>";
}
print "</ul></div>";
}
print "<br style='clear: left;' />";
?>
<?php session_write_close(); ?>
<br style='clear: both;' /><br />
</div>
</body>
</html>
Here is the connect.php file (actual access info removed)
<?php
$testing_server = true;
if($testing_server != true){
$MYSQL_USER_NAME = "removed";
$MYSQL_PASSWORD = "removed";
$MYSQL_DATABASE_NAME = "removed";
$dbh=mysql_connect ("localhost", "$MYSQL_USER_NAME", "$MYSQL_PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("$MYSQL_DATABASE_NAME");
$db = new mysqli('localhost', "$MYSQL_USER_NAME", "$MYSQL_PASSWORD", "$MYSQL_DATABASE_NAME");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
} // if testing server != true
else{
$MYSQL_USER_NAME = "removed";
$MYSQL_PASSWORD = "removed";
$MYSQL_DATABASE_NAME = "removed";
$dbh=mysql_connect ("localhost", "$MYSQL_USER_NAME", "$MYSQL_PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("$MYSQL_DATABASE_NAME");
$db = new mysqli('localhost', "$MYSQL_USER_NAME", "$MYSQL_PASSWORD", "$MYSQL_DATABASE_NAME");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
}//else, testing server credentials
?>
Here is the headers file
<meta name='robots' content='noindex,nofollow' />
<meta name='author' content='removed' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<meta name='MSSmartTagsPreventParsing' content='TRUE' />
<meta http-equiv='imagetoolbar' content='no' />
<link rel='stylesheet' type='text/css' href='css/styles.css' />
<link type="text/css" href="css/custom-theme/jquery-ui-1.9.1.custom.css" rel="stylesheet" />
<script type='text/javascript' src='includes/javascript/jquery-1.8.1.min.js'></script>
<script type="text/javascript" src="includes/javascript/jquery-ui-1.9.1.custom.min.js"> </script>
<link href='https://fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
Aaand here is the menu file
<?php
#MENU
?>
<form method='post' action='index.php' style='float: right; margin: 0 0 0 10px;'><input type='hidden' name='RVC_LOGOUT' value='TRUE' /><input type='image' title='Logout' src='images/icon-logout.png' /></form>
<a href='admin-users.php' title='Manage Users'><img src='images/icon-users.png' border='0' alt='Manage Users' style='float: right; margin: 0 0 0 10px;' /></a>
<a href='listings.php' title='Edit Listings'><img src='images/icon-listings.png' border='0' alt='Edit Listings' style='float: right; margin: 0 0 0 10px;' /></a>
<a href='dashboard.php' title='Home'><img src='images/icon-home.png' border='0' alt='Home' style='float: right; margin: 0 0 0 10px;' /></a>
If anyone can see any reason that this page should load fine the after logging in and then cause every page that uses a session to timeout after trying to leave it, your help would be appreciated.
clicking any link in the menu file causes the page to timeout at the first line, which as I said is the session_start();
EDIT:
I reduced one of the sub pages to just the session_start call and it still causes the browser to time out.
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)