this is what I'm doing currently to create sessions on login page.
if($count==1) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
i know this is very basic and I need to protect the user sessions. Can u provide me some basic tips. If you could edit the code and write the secure one, it would be great. Thanks.
Currently, I am using the email address as session username.
Ask your self this question:
Why am I storing the password when the username is unique in the database
After you have answered that you should of come to the conclusion that its pointless, you can either store the username or the user id in the session when it comes to login systems.
How login systems tend to work is that the user sends the username password from a form to the server where its validated, during the validation process you select the user from from the database where username = post_username.
If there is no rows found the user does not exists so you can directly send output at that point, if the user does exist you then compare the password with the post_password.
the reason why we specifically select the row by just the username is that you should be incorporating some sort of hashing system to add extra security.
if you stored the password as (password + hash) which would be a new string, you would also store just the hash aswell, thus if a user is found then you can create a hash from (post_password + db_hash) and check to see if its the same as the db_password.
this way if your database gets leaked somehow your users credentials are more secure.
once the user has been validated you would store the user id within the session, and then on every page load you can check if the id is within the session and if it is the user is currently logged in and you can select the users data by SELECT * FROM users WHERE id = session_id.
This should get you started.
/*
SecureSession class
Written by Vagharshak Tozalakyan <vagh#armdex.com>
Released under GNU Public License
*/
class SecureSession {
// Include browser name in fingerprint?
var $check_browser = true;
// How many numbers from IP use in fingerprint?
var $check_ip_blocks = 0;
// Control word - any word you want.
var $secure_word = 'random_string_here';
// Regenerate session ID to prevent fixation attacks?
var $regenerate_id = true;
// Call this when init session.
function Open()
{
$_SESSION['ss_fprint'] = $this->_Fingerprint();
$this->_RegenerateId();
}
// Call this to check session.
function Check()
{
$this->_RegenerateId();
return (isset($_SESSION['ss_fprint'])
&& $_SESSION['ss_fprint'] == $this->_Fingerprint());
}
function Destroy()
{
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// Finally, destroy the session.
session_destroy();
}
// Internal function. Returns MD5 from fingerprint.
function _Fingerprint()
{
$fingerprint = $this->secure_word;
if ($this->check_browser)
$fingerprint .= $_SERVER['HTTP_USER_AGENT'];
if ($this->check_ip_blocks)
{
$num_blocks = abs(intval($this->check_ip_blocks));
if ($num_blocks > 4)
$num_blocks = 4;
$blocks = explode('.', $_SERVER['REMOTE_ADDR']);
for ($i=0; $i<$num_blocks; $i++)
{
$fingerprint .= $blocks[$i] . '.';
}
}
return md5($fingerprint);
}
// Internal function. Regenerates session ID if possible.
function _RegenerateId()
{
if ($this->regenerate_id && function_exists('session_regenerate_id'))
session_regenerate_id();
}
}
Common practice is to check the user name and password against the database, then on success store just the user id in the session. Then later, to see if a person is logged in or authorized, you check that user id stored in the session. Though, the session variables are only visible to the server unless you've done something horribly wrong. So its not horrible or insecure but its basically unnecessary.
Edit
Removed bit about cookies, could cause confusion.
Related
On my website, there is a function for logging in and logging out. Upon login, I set the session variables pass (which is hashed password), uid which is the ID of the user logged in and loggedIn (boolean):
$hashedpass = **hashed pass**;
$_SESSION['pass'] = $hashedpass or die("Fel 2");
$_SESSION['uid'] = $uid or die("Fel 3");
$_SESSION['loggedIn'] = true or die("Fel 4");
header("Location:indexloggedin.php");
On every page, I check if the visitor is logged in by
Checking the status of $_SESSION['loggedIn'],
Searching the database for the user with the ID $_SESSION['uid'],
Checking if the hashed password in the database matches the hashed password in the session variable:
$sespass = $_SESSION['pass'];
$sesid = $_SESSION['uid'];
$sql2 = "SELECT * FROM `users` WHERE `id` = '$sesid'";
$result2 = mysqli_query($db_conx, $sql2);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 != 1) {
$userOk = false;
}
while ($row = mysqli_fetch_array($result2,MYSQLI_ASSOC)) {
$dbpass = $row['pass'];
}
if ($sespass != $dbpass) {
$userOk = false;
} else {
$userOk = true;
}
My problem is that this seems to be working on some pages, while it doesn't work at others. For example, when I log in, I am instantly logged in to the homepage, but not to the profile page. However, after a few reloads, I am logged in to the profile page as well. The same thing happens when logging out.
For testing purposes, I tried to var_dump the password variables as well as the userOk status on the index page, and this is where I noticed something interesting. When I log out, the password variables are set to be empty, and $userOk is false, according to what that is shown at index.php?msg=loggedout. But when I remove the ?msg=loggedout (and only leave index.php), the password variables are back to their previous value, and I am no longer logged out... After a few reloads, I am once again logged out.
Why is my session variables not working as expected? It feels like as if it takes time for them to update, which is very weird. I have tried with caching disabled (both through headers and through the Cache setting in my browser).
Just tell me if you need more info.
You have initialization session_start() on every Site?
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
After contacting my hosting provider, it was actually a hosting issue. It is now resolved!
Thanks,
Jacob
I'm coding a PHP script and I need a login. So I want to check the input against a database with username and password. Is the best way to do it by doing a query where I compare if the post data is the same (SQL function 'like') as in the database? After that I count the mysql rows. If it's zero, I deny the login. If it's one, I allow the login.
Is that the common and correct way of doing it or are there better ways? I want to have the best modern way. That's the reason why I'm using HTML5 too.
Some part of my code. Setting up cookies for the future cookie log-in and also setting attempts in the session to show the captcha if attempts exceeded certain number of logins.
(Hope you can understand it a bit)
Signin call
if($this->check_signin_errors()) {
if($this->signin($this->user_email, sha1($this->user_pass))) { //$user_pass hashed
header("Location: /account/");
exit();
} else {
$this->generate_captcha();
}
return true;
}
Signin function
private function signin($user_email, $user_pass) {
global $con;
$query = mysqli_query($con, "SELECT *, COUNT(id) FROM `accounts` WHERE `user_email` = '".mysqli_real_escape_string($con, $user_email)."' AND `user_pass` = '".mysqli_real_escape_string($con, $user_pass)."' AND access_level >= '0'");
$result = mysqli_fetch_assoc($query);
if($result['COUNT(id)'] > 0) {
$_SESSION['account_logged'] = true;
$_SESSION['user_id'] = $result['id'];
$_SESSION['user_email'] = $result['user_email'];
$_SESSION['user_pass'] = $result['user_pass'];
$_SESSION['access_key'] = $result['access_key'];
$_SESSION['access_level'] = $result['access_level'];
$this->set_cookie('cookie_name', '1/'.$_SESSION['user_email'].'/'.$_SESSION['user_pass'], 7776000);
$_SESSION['attempt'] = 1;
return true;
}
$_SESSION['account_logged'] = false;
$_SESSION['attempt'] = $_SESSION['attempt'] + 1;
$this->throw_error(5);
return false;
}
The most current approach would be to use the PHP 5.5 password hashing functions.
And because not everyone uses 5.5 yet, there is a library that implements it for earlier PHP versions.
Because hashing passwords uses a dynamic "salt", a random string, generated for each user individually, when logging in you actually need to read the user database to get the current hash, because when you want to compare the login password, you need the hash as second input to the password_verify() function.
So actually you try if you find the user in the database (do not use "LIKE" here, this is for searching with placeholders - your user should be able to type his username correctly). If none is found: no login. If two are found: You should add a unique index to the username, otherwise you'll have two users with the same name.
If one entry is found, you read it, compare the hashes, and then allow him further.
I'm using a basic cookie system for the "remember me" part of a log in form. Here is the code:
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect('localhost','root','');
mysql_select_db('phplogin');
$query = mysql_query("SELECT * FROM utilisateurs WHERE NomUtilisateur='$username' AND MotDePasse='$password'");
$rows = mysql_num_rows($query);
if($rows==1)
{
if($_POST['checkbox'])
{
setcookie('username',$username,time()+3600);
header('Location: membre.php');
}else{$_SESSION['username']=$username;header('Location:membre.php');}
}else echo "Something something error";
}else echo "Something something darkside";
}
I'm not quit sure if I need to secure the cookie and if yes, how to do it? All I really want to do is not allowing people to log in in another user account with a fake cookie or put sensitive information on the clear in the cookie.
Currently anybody can log himself if he knows the username of a user. Even if a cookie is set you need to have a process to identify users that they are genuine clients..like for ex., when a user logs in you can save a random alphanumeric string saved in the cookies and your DB against that user, and the next time you cross check the string with the value in your DB and remember to change the alphanumeric string after every X days, this prevents attackers from copying someone’s cookies and using them to login. Something like this do
$uniquekey = 'A234W';
$randomstring = sha1(strval(rand(0,microtime(true))+ $uniquekey + strval(microtime(true))));
setcookie( 'loginID', $randomstring, time()+60*60*24*7,'/', 'www.yoursite.com', false, true);
and when reading from cookie use mysql_real_escape_string to filter any malicious code
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
$goHere = 'Location: /index2.php?id=' . $id;
header($goHere);
exit;
}
I have the following code that once logged in, it $_GET the id and prepends to the url like index2.php?id=5 . How do I keep this id=5 in the URL no matter WHAT link they click on??
This id is grabbed from this:
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
What I want to do
Well way i have it setup, you login, it then sends you to the homepage such as index2.php?id=[someint] , if you click another link say 'prof.php', it removes the id=[someint] part, I want to keep it there in the url, so as long as a user is LOGGED in -- using my code above, the url might read: index.php?id=5, then go to another page it might read prof.php?id=5, etc, etc. This integer would obviously be dynamic depending on WHO logged in
Instead of passing around an ID in the URL, consider referring to the id value in the $_SESSION variable. That way the user can't modify the URL and see data they aren't supposed to see (or much worse), and you don't have to worry over appending it to every URL and reading it into a value every time you go to process a script. When the user logs in, you determine their ID - read it from a database, determine it realtime, whatever. Then store it in the $_SESSION and refer to it as needed. You can even use this as part of a check to see if the user is logged in - if they have no $_SESSION['id'] value, something is wrong and you make them log in.
The query string isn't the place for that, for a whole host of reasons. The most obvious one is that I can log in with a valid account, then change the number in the URL and it'll think I'm someone else.
Instead, just continue using the session as it's the proper way.
If you REALLY want to do it, you'd probably want to write a custom function for generating links
function makeLink ($link, $queryString = '')
{
return $link . '?id=' . (int) $_SESSION['id'] . ((strpos($queryString, '?') === 0) ? substr($queryString, 1) : $queryString);
}
called like
Click me
As a basic auth example using the ID...
<?php
// Session start and so on here
if (!isset($_SESSION['id']))
{
// Not logged in
header('Location: /login.php');
exit;
}
http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ is a pretty straightforward full example of it.
i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? » Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.