How to use session variables to output logged in username and properties - php

I'm building an application and have just added a Login page which works well, communicating with a "username" and "password" field in the database. After logging in, it takes you a page users are authorized to see.
Is there a way I can display "Welcome, xxx" to the particular user logged in at the next page? And more importantly, output detailed information of the logged in user on that next page? More technically, to output properties of the username which are in different tables in the database.
Now I know I should begin with:
<?php
session_start();
$_SESSION['username'] = $user_name;
?>
But how do I specify assigning the value of "$user_name" to the value inputted in the username textbox.

Use this
$_SESSION['user_name'] = $_POST['username'];

I think using sessions is unnecessary for this task.
Simply search the database for the user's name once they log in and display this back to the page. Only store what's needed in sessions, databases are a more efficient storage medium.

Related

Logging in and bypassing login screen

So I have set up my first website that uses registration and login and it has been implemented using php and mysql. My problem is that if a user has obtained the URL of the pages that he accessed after passing the login page, he is currently able to copy and paste those pages in the URL and bypass the login.
QUESTION: Is there any way I can ensure that an actual login has taken place?
My host 000Webhost (free) allows folders to be password protected but I do not know how or if I could tie this into my user database.
This is the first question I have asked on this subject..please be kind.
Yes, there are easy ways of checking if a user is logged in and the best way is to use the $_SESSION superglobal. When you use the session superglobal, you are basically saving information onto the server about a specific user, and at the same time saving a cookie on the users computer that uniquely identifies him as long as the session is valid (which is usually 30 minutes). In plain English, the php developers made a superglobal that would basically make it super easy for developers to "maintain state" without having to do extreme amounts of code.
This is how you would use the session superglobal. At the top of every page of your website, you would have this portion of code (even above <!DOCTYPE html>):
<?php session_start(); ?>
What this does (among a lot of other things) is saves a cookie on the users computer identifying him uniquely while the session is valid. NOW... on the page that the user enters after having logged in, you would have code similar to the following:
<?php
$username = $_POST['username'];//obtaining username from form
$password = $_POST['password'];//obtaining password from form
// i did not include any encryption code in this example
// so that the example is easier to understand, but keep in mind
// that encrypting your users passwords is super important
//for security reasons, I used prepared statements and binding parameters
//to compare the password and username obtained from the form with
//those in the database (in order to prevent sql injection):
$sql = "SELECT 1 FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
if ($stmt->rowCount()>0)//if a row was found, then you know this user exists
{
//here I am saving information in the session super global that
//can be used to not only identify if a user is logged in on each
//page, but also to see which user is logged in, since often
//you want to give a user his own control panel or other features.
$_SESSION['authenticated'] = TRUE;
$_SESSION['username'] = htmlspecialchars($username);
}
?>
Now on every page that you have, you would include the following code:
<?php
if (isset($_SESSION['authenticated']))
{
echo "Hello there ".$_SESSION['username']."!<br>";
}
?>
The previous code would then echo something like "Hello there John!" if the users name was John. From here, you could include any code you want inside those brackets that you only want users logged in to see SO USERS THAT are not logged in will hence not be able to view that part of the website, even though they would see the sites logo, and everything else that isn't inside the if conditional. Also, the previous code does not have to be at the very top, only <?php session_start(); ?> needs to be and this is because of reasons regarding how the HTTP protocol works.
Let me know if this helped or if you have any other questions.
Webeng's answer above has most of what you need, but you need to look into how you made your database connection so that you can use your prepared statements properly. Look up PDO or mysqli database connections.
He's completely right about using SESSION variables to keep track of whether or not a user is logged in, and about using prepared statements for SQL.
The one thing I would change about his answer is the top of each page. I would use this instead, so that if a user is NOT logged in when the page loads, they are sent back to the login page:
if (!isset($_SESSION['username'])) { header("Location: login.php"); }

What is the proper way to utilise sessions for authentication in php?

Currently what I do is store the user's username after a sucessful login into a session variable.
$_SESSION['session_loggedin'] = $post_username;
post_username is the POST from the submit form.
Then i use this session variable to check if it is set, to see if a user is logged in. I use the value of this variable to show user-specific content.
<?php
if (isset($_SESSION['session_loggedin'])) {
?>
LOGOUT
<?php
}
?>
Is this how sessions are meant to be used? Is this a right way to securely show content? How do I prevent hijacking?
Thanks
You're almost there! But you are supposed to store the user's id on session. You query the database where username is equal to post username and password is equal to post password, the count the number of rows return! From there you store the user's id on session.
To see how PHP sessions are used please go to:http://www.w3schools.com/php/php_sessions.asp
. No since i could go onto your other pages (assuming you have some) and insert a username i.e. if John Smith Logged in with a Password:password thats fine but i could go onto you website and put John Smith as $_SESSION['session_loggedin'] and be away with his account. You may ask but how will he know about $_SESSION['session_loggedin'] if he is smart he would create a user and capture the sessions and see what he needs to input to gain control of another account. Instead of a username i would recommend a hashcode!
See this for hijacking:What is the best way to prevent session hijacking?

Login form and accessing pages for admin/users PHP

I created a table which has one admin and can have multiple users. When the user is logged in, he can perform CRUD operations and users can only view the data when they are logged in. BUT there is a problem because i don't know how to omit the regular user from simply entering the address in the address bar and accessing the page he is not supposed to (the page only admin has access to). Since I am new to PHP, I know I am supposed to use sessions for this, but I don't know how. What is the function I need to use, which column from the table (userid or the type - admin and user - those are the user types from the table) and where should I place the if statement in my code?
you can use header and session..
when a user logs in .. save his/her id in session variable lets say $_SESSION['user_id']...
and in all the pages which only admin can access put a if condition like..
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != '')
{
$_SESSION['error_message'] = 'Access Denied';
header('location:user_page.php');
exit();
}
and in user_page.php echo that session error message and unset it
echo $_SESSSION['error_message'];
unset($_SESSION['error_message']);
let me know if you want any further guidance..
How do you "log in" your user? You are using core php or some framework? More details please.
In plain vanilla PHP... (Not Zend or Symphony etc)
You can store details in the session, its a global called $_SESSION, and is available when a session is started.
This tutorial may help; http://html.net/tutorials/php/lesson12.php
Just remember anything in a session is cleared when your browser is closed - but thats usually a good thing for user activity.
Persistence across browser usage, would be storing the session in a cookie.
pass user type to session
$_SESSION['usertype'] = $user['usertype'];
and check the session
<?php
if($_SESSION['usertype'] = "user") {
load your user page
}
else
{
load admin page
}
?>

authentication safely

So I currently store a token and user ID whenever a user logs in. The token is stored in the user table and in a COOKIE.
So user 1 logs in and the following details is stored in a COOKIE and database on his
computer:
id
randomly generated token
whenever he logs in a different token is generated.
To authenticate the user, everytime he accesses my site, I check to see if the token matches with that stored in the database for the specific cookie.
But the problem is that constantly checking the database is a waste of resources but how do we make sure that user is who they say they are? I can't just store his ID in a cookie because he could easily change the ID and get access to another user's information.
thanks!
Could you use a $_SESSION variable such as: $_SESSION['id'] = $randomstring;
Then at the top of each page check if the variable is set:
<?php if(isset($_SESSION['id'])) $loggedin;
else $logout;
?>
Use session_start() which handles the logistics of checking the cookie and validating that the data is actually for that user's session.
You have to start the session before you can use $_SESSION but that's one way to store session data.
http://php.net/manual/en/function.session-start.php

Passing arguments via header in php

I have 3 files:
login.html
login_check.php
welcome.php
In login.html when the username and password is entered and submit button is clicked login_check.php checks whether the username entry is in the database on the basis of $_POST['username'] and some SQL query. Now I have put the following code at the bottom of login_check.php
login_check.php:
header('Location:welcome.php')
But I want to pass $_POST['username'] from login_check.php to welcome.php so that I can make use of $_POST['username'] in my welcome page. Is there any way by which I can pass an argument like in the above case?
Use session instead because you would be showing the user's name everytime on the welcome page no matter which page you land at welcome page.
You can set the session on login_check page like:
session_start(); // this should be on top of login_check file
// this goes just before redirect line
$_SESSION['username'] = $_POST['username'];
Now on the welcome page, you can show username like:
session_start(); // this should be on top of welcome page.
echo `Welcome ` . $_SESSION['username'];
This can be done using QUERY_STRING (I am sure you have seen it before - these ?'s and &'s in the address bar), but you shouldn't do it as it's just insecure.
A session is the common way to store a username after login and authorization in general.
The session should only be used for session data - not for data relating to a specific page transition. However recording the fact the user has been authenticated and the the username with which they authenticated is session data.
So while you shouldn't use session data to pass information from login.php to login_check.php, in login_check.php, if the authentication is succesful, then you should then store the authenticated username in the session.
While, as Col. Shrapnel says you could do:
header('Location:welcome.php?username=' . urlencode($_POST['username']));
This is trivial to circumvent - you just need to type welcome.php?username=admin into your browser to break the security.
If that's still not clear, consider the situation where the user has two browser windows open at the same time, navigating through different parts of the site (i.e. using same session data). If both browser submit data at the same time which is written to the session and you're not sure of the outcome, then you probably shouldn't be keeping the data in the session.
HTH
C.
Using the header(www.xxx.com?action='') would be the only way to transfer without storing it as a session.

Categories