We have a login form that is processed by php and ajax. The ajax sends a request to the php page with the username and password to be logged in. It gets a response and if it's correct and working info, it logs them in:
The php page that takes requests has this code:
echo (checkLogin($_POST['user'], $_POST['pass']) ? 'true' : 'false');
if(checkLogin($_POST['user'], $_POST['pass']) == true)
logIn($_POST['user'], $_POST['pass']);
The functions used in that statement:
function logIn($user, $pass)
{
$_SESSION['sid'] = md5(md5($user) . md5($pass));
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
}
function checkLogin($user, $pass)
{
$user = strtolower($user);
$pass = strtolower($pass);
$res = mysql_query("SELECT * FROM users WHERE username='".$user."'");
if(mysql_num_rows($res) == 1)
{
$data = mysql_fetch_assoc($res);
if($data['pass'] == aCrypt($pass))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Now, it seems that the session is started and only able to be seen AFTER the user reloads the page. We need it to start the session right on the page...would we need to refresh the entire page with ajax? I don't really know where to go from here.
You probably want to use the Post-Redirect-Get pattern; after the user is successfully authenticated, use a redirect to send him to a new page.
As I noted above, please look into fixing the SQL injection and session fixation vulnerabilities in your code as well.
Related
I've finally got the courage to make a user login system after who knows how long of putting it off. My only problem is that when I submit the login form it reloads the page and it says that I am logged in, great.
However if I reload the page or go to another page and come back to the original page it forces me to login again. Can anyone help with this? I have a session_start() in the base file that is included in all other page files before the database connection.
I then have the following code for my user login side of things, which as I said, works the first time around, but after that any other interaction will essentially log me out. Any help with this?
The user page which logs you in and creates the session...
Please note that this isn't a live environment so security is being put on the bench for now. However I am aware I will need some security measures in place in the future though.
// Check if the user is logged in or not
if((!empty($_SESSION['loggedin'])) && (!empty($_SESSION['username']))) {
$loggedin = true; // The user IS logged in
} else {
if(isset($_POST['login'])) {
// The login form has been submitted
if((empty($_POST['username'])) || (empty($_POST['password']))) {
// If either username or password fields are blank
$loginfail = true; // If the user could not be logged in
if(empty($_POST['username'])) { $nousername = true; }
if(empty($_POST['password'])) { $nopassword = true; }
} else {
// Username and password field were filled in okay
$username = $_POST['username'];
$password = $_POST['password'];
$checklogin = mysqli_query($sql, "SELECT * FROM users WHERE username = '$username' AND password = '$password'") or die($checklogin . "<br/>" . mysqli_error($sql));
if(mysqli_num_rows($checklogin) == 1) {
// If the login details match up, log them in
$loggedin = true; // The user IS NOT logged in
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = 1;
} else {
// If the login details don't match up, don't login
$loginfail = true; // If the user could not be logged in
}
}
}
}
Thanks!
I have a user authentication function in PHP that checks user information when logged inn. I have placed it in the header of every pages where a user is required to be logged in. After further investigation when moving my web page to a dedicated Windows Server this week, I noticed that page load is increased by this particular function. Talking about seconds.
My experience with PHP is not so good that I can re-write the function or think about a better solution. I can definitely see it's a heavy thing going on there; checking database, user agent, hash and etc every time a page loads. So my question is: is it possible to run this function only one time per session? In that case, how should it be structured? What would be a better solution?
function login_check($mysqli) {
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
FROM members
WHERE id = ? LIMIT 1")) {
// Bind "$user_id" to parameter.
$stmt->bind_param('i', $user_id);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if ($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
You can see the whole script at
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
You should only be querying the database once per session for that user. Instead, just create a simple script at the top of each page you need to protect that checks if they are signed in or not. For example:
<?php
session_start();
// If user_id is NOT SET then they are not signed in
if (!isset($_SESSION['user_id'])) {
// Send them somewhere else (login page maybe?) and exit
header("Location: somepage.php");
exit;
}
// If they made it here, they have a valid session
// TODO Code
I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();
hi I have a login system for my admin section that i have a problem with, the problem is that the first time the user attempts to login, the $_SESSION isn't passed to the target page,
on the second attempt it works fine, this is what is called on the login page
$membership = new Membership();
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
in the class memebership
function validate_user($un, $pwd) {
$ensure_credentials = $this->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['id'] = $ensure_credentials;
header("location: ambassadorUpdate.php");
die;
} else return "Please enter a correct username and password";
}
i've checked the code when i don't then send to ambassadorUpdate and the SESSION is set however if i use the header to redirect to page then the first time the SESSION is not
there is a session_start on both pages,
the code runs fine when all the pages where in the same folder, however i am getting this problem when i have organised them in a separate admin folder however all of the files are included correctly,
any ideas greatly appreciated many thanks
Try to modify:
$membership = new Membership();
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
if ($response == true){
header("location: ambassadorUpdate.php");
} else echo "Please enter a correct username and password";
in the class memebership
function validate_user($un, $pwd) {
$ensure_credentials = $this->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
echo 'workied';
$_SESSION['status'] = 'authorized';
$_SESSION['id'] = $ensure_credentials;
echo $_SESSION['status'] . $_SESSION['id'];
return = true;
} else return false;
}
I can't create an comment, so i write an answer.
Have you check session_start() in ambassadorUpdate.php. Does your browser accept cookies?
If not, it is usefull to use "location: ambassadorUpdate.php".?SID or you can use session_name()=session_id() instead of SID
Hope this helps.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP session seemingly not working
I'm currently coding my own CMS for fun but when I use $_SESSION, it doesn't work. The session isn't saved...
There's my code:
<?php
include('header.php');
if (isset($_SESSION['logged_in']))
{
$link = 'profile.php';
$link_name = 'Profile';
}
else
{
$link = 'login.php';
$link_name = 'Login';
}
if (isset($_POST['action']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password = md5($password);
$user = mysql_query("SELECT * FROM users WHERE `username`='".$username."'");
if (mysql_num_rows($user) == 1)
{
while ($userinfo = mysql_fetch_array($user))
{
if ($userinfo['banned'] != true)
{
$_SESSION['user_id'] = $userinfo['id'];
$_SESSION['username'] = $userinfo['username'];
$_SESSION['logged_in'] = "true";
header('Location: index.php');
}
else
{
header('Location: login.php?error=banned');
}
}
}
else if (mysql_num_rows($user) == 0)
{
header('Location: login.php?error=not-found');
}
}
?>
In the code, I get the user information in my database then I check if the user isn't banned. If not, I set my $_SESSION[] and I redirect to the home...
You need session_start() at first.
you should call session_start() in the beginning of the script. make sure you call it on every page you need the access to session variables as well
Make sure session_start() is being called. Use Tamper Data to check the Headers for Sent and Received requests. Your looking for the Set-Cookie Header from the server and the Cookies Header from the client. This should contain your PHPSESSID. If you don't see this then your session is not started. Good Luck!