Redirecting logged in users - php

I have created profiles for users so that when a user logs in they are redirected to their own profile page.
login.php (relevant code only)
$MemberID = user_id_from_username($username);
$_SESSION['MemberID'] = $username;
header('location: member.php?username='.$username);
member.php
if (logged_in () === true){
echo "Welcome, ".$_SESSION['MemberID']. "!<br><a href='logout.php'>Logout</a>\n<a href='index.php'>Back to homepage</a></p>";
}
if(isset($_GET['username']) === true & empty ($_GET['username']) === false) {
$username = $_GET ['username'];
//check if user actually exisits
if (user_exists($username) === true) {
//get username from user id
$MemberID = user_id_from_username($username);
$profile_data =user_data($MemberID,'Name','Address','Postcode','DOB','Mobile','CoinsAvailable','Email','profile','OddJobName','Description','CoinValue','DaysAvailable');//Need to pull out stuff from oddjob table
echo $MemberID;
}else{
protect_page();
}
}
relevant functions:
function user_data($MemberID){ //pass in memberid to get info about user
$data = array();//data to be returned
$MemberID =(int)$MemberID;//creating int from this input
$func_num_args = func_num_args(); //count number of arguments from user data on init.php
$func_get_args = func_get_args();
if ($func_num_args >1) { //if more then 1, unset the first element of array
unset($func_get_args[0]);
$fields = '`' . implode('`,`', $func_get_args) . '`'; //taking array and converting to string
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `member`,`oddjob` WHERE member.MemberID = oddjob.MemberID AND member.MemberID = $MemberID"))or die (mysql_error());
//echo $MemberID;
return $data;
}
}
function logged_in() {
return (isset($_SESSION['MemberID'])) ? true : false; //Email
}
if (logged_in() ===true) {
$session_MemberID = $_SESSION['MemberID'];//grabbing value from login
$user_data= user_data($session_MemberID,'MemberID','Name','Address','Postcode','DOB','Mobile','CoinsAvailable','Email','Password','RepeatPassword','OddJobName','Description','DaysAvailable','profile');
exit();
}
All this code allows the user to be redirected to their own page, when they login their name is displayed along with other $profile_data information. Now I want the user to be able to update their own info by clicking on a link to update_info.php. But I don't know how to get the members username to appear in the URL when they visit update_info.php like it does when they log in.
In the member page (where the link is) I tried:
<a><?php header('location:update_info.php?username='.$username)?>">Update info</a></p>
But now when the user logs in they are redirected to update_info.php instead of member.php. Can anybody tell me how to fix this? Thanks.

Do you mean:
Update info
This passes the $username to the update_info.php page

Maybe you wanted to write this?
Update info</p>

All right.
Lets explain the basics on how to build a -basic- authentication. And then extend it to a safe one :)
1 - user logs in : You check the database if the credentials are allright.
If Yes -> $_SESSION['loggedIn'] = true;
2 - On every page you want to check if the person is logged in; you put a check:
if(!$_SESSION['loggedIn']) { header('location:login.php');}
Some food for thought:
You don't want to store 'just' a boolean on the clientside to check if logged in. You better generate a random session-id-string. Store this in a database and store this id in the $_SESSION['loggedin']. Instead of the simple check of the value of $_SESSION['loggedIn'] you now look up the stored session ID in the database for existince and availability.
Post Scriptum:
Don't nest functions in functions in functions.
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROMmember,oddjobWHERE member.MemberID = oddjob.MemberID AND member.MemberID = $MemberID"))or die (mysql_error());
This is not readable for us, but especially not for you. You better write it like this:
$sql = "SELECT $fields FROMmember,oddjobWHERE member.MemberID = oddjob.MemberID AND member.MemberID = $MemberID";
$res = mysql_query($sql) or die(mysql_error());
$data = mysql_fetch_assoc($res);
Post Post Scriptum:
Stop using the mysql_* functions in php. See the red box on this website? These functions are not supported anymore. And you better start using PDO; which by the way has also some checking (mysql injection) standard build in; and much more!

Related

Implementing a check for user levels

I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP

$_Session variables not accessible on the same page they are created

My issue is that for some reason on the login.php page of my website, I initialize some $_Session Variables from my users table in the corresponding database, but while these variables seem to function properly on other pages I can't do anything with them immediately after initializing them, because they don't seem to exist. This is an issue because I would like to reference the variables I have defined to create other session variables for efficiency, and because I would like to use it for a welcome message like the simple example shown in my code. Here is the code in question:
if(isset($_POST['user_email']) && !empty($_POST['user_email']) AND isset($_POST['user_pass']) && !empty($_POST['user_pass']))
{
$email = mysqli_real_escape_string($link, $_POST['user_email']); // Set variable for the username
$password = mysqli_real_escape_string($link, sha1($_POST['user_pass'])); // Set variable for the password and convert it to an sha1 hash.
$result = mysqli_query($link, "SELECT user_email, user_pass, user_active FROM users WHERE user_email='".$email."' AND user_pass='".$password."' AND user_active='1'") or die(mysqli_error($link));
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_uuid'] = $row['user_uuid'];
$_SESSION['user_level'] = $row['user_level'];
$_SESSION['user_rank'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_uuid'] . '. <br />Proceed to the forum overview.';
}
}
}
I have session_start(); at the top of my connect.php which is included at the top of the signin.php doc.
The result of this code on this page is something like:
Welcome, .
Proceed to the forum overview.
However if I run it on a different page on the site it properly prints, i.e.:
Welcome, username.
Proceed to the forum overview
Thanks.

Wrong session value when reading

I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?
As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.
I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.

PHP Error Form - Leave Contents of Form on Redirect

I have a simple login form in which if an error occurs such as wrong password, I need it to be able to remember the username which was entered. Would I Go about doing this PHP or Javascript as I am not allowed to use JQuery.
My current PHP - (Not Including the HTML Form)
<?php
//MySQl Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("clubresults") or die(mysql_error());
//Initiates New Session - Cookie
session_start(); // Start a new session
// Get the data passed from the form
$username = $_POST['username'];
$password = md5($_POST['pass']);
// Do some basic sanitizing
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//Performs SQL Query to retrieve Login Details from DB
$sql = "select * from admin_passwords where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
//Assigns a Variable Count to 0
$count = 0;
//Exectues a loop to increment on Successful Login
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
//If count is equal to 1 Redirect user to the Members Page and Set Cookie
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
header("Location: members.php"); // This is wherever you want to redirect the user to
} else {
//Else Echo that login was a failure.
die('Login Failed. <a href=login.php>Click Here to Try Again</a>');
}
?>
Any help would be appreciated. Cheers
You could use $_SESSION or $_COOKIE.
For $_COOKIE, just use setcookie(...) (for localhost, on $domain, use false)
For $_SESSION, just set it like any other array
To check for existence of the value, use isset(...).
Don't use session variable..you can achieve this by passing username as parameter to login form when login fails its means..
//Else Echo that login was a failure.
die('Login Failed. Click Here to Try Again');
in form
if (isset($_GET['username']) set it into login username field otherwise keep it empty

Mysql result to set session variable

I want to use the result of a mysql query to set a session variable however at present I am struggling to make it set.
My code I have is:
<?php
ob_start("ob_gzhandler");
?>
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
I am then testing the session variables with:
<?php
session_start();
echo "Login Status is:".$_SESSION['logged_in'];
echo "<br/>";
echo "Auth status is level:".$_SESSION['auth_lvl'];
?>
On my testing page the session logged in works fine displaying the correct information however the auth lvl variable displays nothing.
I can only assume that I am not calling the information correctly that I am setting the variable with in the first place.
Any help would be appreciated.
Alan.
Something I have notice and I have been trying the suggestions is that if I set a definative rather than trying to retreive a value from the database that value will return on my test page. i.e.
$_SESSION['auth_lvl'] = 'test';
This tells me it is the way in which I am pulling the data from the database and trying to set it as $_SESSION['auth_lvl'] that is causing the problem.
Found the problem.
the code read:
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['Auth_lvl'];
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
Because I had used mysqli on this code I had not notice that on the //ADD THIS SET OF LINES piece of code that an 'i' was missing. When I changed the code to:
$data = mysqli_fetch_assoc( $result );
Everything fired into life.
Thanks for your help guys.
I can't see anywhere that you have assigned $Auth_lvl with a value, so when you do:
$_SESSION['auth_lvl'] = $Auth_lvl;
It's presumably getting assigned null.
I'm not seeing where you are setting $Auth_lvl. After you check for the results being there, and rows, you're going straight to setting a session variable against an empty variable.
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['auth_lvl']'
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
Then with your logged_in session variable, you're setting it as a boolean, true, and then trying to echo it out as normal text.
if ( $_SESSION['logged_in'] ) { echo "Login status is: True"; }
I hope that helps.
-Dan

Categories