$_SESSION equals value from database? - php

when a person logs into my site i need to check a value in a database for their roleid, and dependent on that i need to allow/deny access to a page.
I have this code but it says that the $_SESION variable 'Access' is undefined, i cant see why?
$email = mysql_real_escape_string($_POST['email']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM person WHERE email = '" . $email . "' AND password2 = '" . $password . "'");
if (mysql_num_rows($checklogin) == 1) {
$row = mysql_fetch_array($checklogin);
$roleid = $row['roleid'];
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['Access'] = $roleid;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
This is the if statement that is saying the session in undefined:
if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email']) && $_SESSION['Access'] == '2')
EDIT
Sorry, should have mentioned, session_start() is called in my base.php file which is included in this file.
EDIT
I don't know what the problem is, i can assign the variable $email to the other session variable and display that so the user can see who they are logged in as?
Does anybody have any suggestions? Both of the other session variables work fine.

From the code you have posted, you are missing session_start()
If this is not within a framework that performs this for you, it must be called on every page that will utilize the session before any session calls are made.
I assume the error is occurring after the redirect, in your logic that is checking for it using isset() or empty(). Add session_start() to both pages before any session logic is performed.
EDIT:
Ok, you have session_start(). Can you print_r() your $_SESSION and check the output?
Also, the file you mention that runs the session start should be included in both files, as its necessary for setting and checking values from the session.
Make sure before running any empty() conditionals, you also run isset(). Empty does not check if the key is present.
EDIT AGAIN:
Is it possible your value for $y isn't coming out of the database as a single value? can you die() at that point, just printing the value of $y out to see what is output?

Just add another check to your if statement, !empty($_SESSION['Access'])
if (!empty($_SESSION['LoggedIn'])
&& !empty($_SESSION['Email'])
&& !empty($_SESSION['Access'])
&& $_SESSION['Access'] == '2')

Check the spelling of $row['roleid']. Is the field name in the database table EXACTLY like it ?
Change
SELECT * FROM person WHERE
to
SELECT roleid FROM person WHERE
see if it breaks... :-)

This might not be related to your problem but I think it's worth mentioning: Your username / password SQL statement can be dangerous. Although you escape the input variables it is usually better practice to do it this way:
$checklogin = mysql_query("SELECT * FROM person WHERE email='".$email."'");
$row = mysql_fetch_array ($checklogin, MYSQL_ASSOC);
if (mysql_num_rows ($checklogin) == 1 && $row['password'] == $password)
{
// you are logged in
}
else
{
// wrong email or password
}
Reason being is that your current statement only needs to return ANY row in your table whereas this statement needs to return one specific row in the table.

Related

How do I double check my PHP signin form

I made a signin form that will look through the database and find a match to the user's credentials, but how do I fix this code so it will relocate the page if there is no match.
<?php
session_start();
include_once 'includes/dbh.php';
$username = $_POST['u_name'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM users;";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row['username'] && $password == $row['password']) {
$_SESSION['username'] = $username;
header("Location: second_index.php?signinSuccessful");
}
if ($username != $row['username'] && $password != $row['password']) {
header("Location: index.php?NotSucessful");
}
}
I tried putting the code inside of the loop, but I know that can't work, and if I put it outside of the loop, It redirects even if the credentials are correct. Please help. Thanks
First of all, this is totally wrong, you're looping trough all the users to see if the user exist, instead of that sql statement try $sql = "SELECT * FROM users where user='$user' and password='$password'";
And to avoid any data breach in that sql statemen you have to serialize the user and pass like that before adding it to the statement
$user = mysql_real_escape_string($conn, $user);
$password =mysql_real_escape_string($conn, $password);
Then you only check if the fields aren't empty (which means the user exist)
You are getting all the users from the users table and checking each record manually in php.
The reason why your code doesn't work is because the while loop doesn't check all the users in user table. If the first record in the retrieved table data doesn't match with entered username and password, it will go to 2nd if block and redirect.
You should change your query to filter by user-entered values.
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD='password'
And later check in php if any record is returned. If any record is returned, it is a valid user, else redirect the user to failed authentication page.
As a good practice, make sure to use parameterized query.
Update Replace the while loop and block with this.
if(mysqli_num_rows($result) > 0){
// valid user
}else{
// invalid user
}
Why do you need while loop in this case when you fetching data from database? Using sql and make the database fetch the only one correct answer, don't make server site do unnecessary work.
I propose just do simple fetch then if check, no need for while loop at all.
Your logic is always redirect to index.php when username password not correct so of course it will always do so when your while loop on server do not hit the correct user.

PHP Multiple Restricted Access

I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)

PHP program is negating a function?

So basically what I have set up here is a very simple and generic log in. I have the entire code copy and pasted because maybe its important somehow. However-
$user = mysql_real_escape_string($_POST['User']);
$pass = mysql_real_escape_string(md5($_POST['Pass']));
$conn = mysql_connect("localhost", "root") or die(mysql_error());
(mysql_select_db('fireworks', $conn));
$ask = "SELECT * FROM name WHERE (User = '" . $user . "') and (Pass = '" . $pass . "');";
$result = mysql_query($ask);
The segment of code below is completely ignored! When I press log in (From the index page) It is suppose to run a series of checks. If the user decides to not put anything inside the user and password text boxes then it is suppose to return the string show below:
if (strlen($user) < 1){
if (strlen($pass) < 1){
print "<p class = 'Back'>Epic Fail</p>";
print "<p>You forgot to put in your Username or Password.</p>";
}
}
(^Up until here) But it doesn't. Instead its just a blank page. But everything else works fine. If I type in a fake user then it returns "YOU FAIL!" If I type a valid user it returns "WELCOME BACK."
if (strlen($user) >= 1){
if (mysql_num_rows($result) >= 1) {
while ($row = mysql_fetch_array($result))
{
print "<p class='Back'>Welcome back</p><p>" . $row['User'] . "</p>";
}
}else{
print "YOU FAIL!!!";
}
}
Any suggestions? EXTRA NOTES: The database is called fireworks the table is called name there are three columns in the name table. nameID, User, and Pass. (Idk how this is useful but sometimes it is.)
Your code:
if (strlen($user) < 1){
if (strlen($pass) < 1){
print "<p>You forgot to put in your Username or Password.</p>";
}
}
In actual fact, this won't check for $user or $pass being blank; it will only give the error message if both of them are blank.
Each test is okay on its own, but the way it's written, the test for $pass will only be run if the $user test has already given a true result.
What you need to to is write them together with an or condition, like so:
if (strlen($user) < 1 or strlen($pass) < 1){
....
}
Hope that helps.
try this:
if (strlen($user) < 1 || strlen($pass) < 1){ .... }
You're nesting the ifs, so the "Epic Fail" is only displayed when both the user name and password aren't entered.
You might want to change it to this:
if (strlen($user) < 1 || strlen($pass) < 1)
{
print "<p class = 'Back'>Notice</p>";
print "<p>You forgot to put in your Username or Password.</p>";
}
In the documentation of mysql_real_escape_string it says that it will attempt to connect to database for the character set. If you did not connect to database at all before the check it might very well be the case. You can check if error reporting to see if it returned E_WARNING level error.
Another thing is that you should avoid database calls when it is not needed. If thats the whole part of the important code, you should call both checks before you try to escape them and continue with database stuff. Also, empty() function might help you as well.
if(!empty($_POST['User']) || trim(strlen($_POST['User'])) < 1) {
// database stuff
}

Keep a given ID in URL upon successful login

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.

$_SESSION['user'] not working

SO this is the code for logging and and where I set things
<?php
session_start();
$_SESSION['user'] = "kjkj";
$_SESSION['pass'] = "";
$error = $user = $pass = "";
if (isset($_POST['user'])) {
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "") {
$error = "Not all fields were entered<br />";
} else {
$query = "SELECT store,c_pass FROM store
WHERE store='$user' AND c_pass='$pass'";
if (mysql_num_rows(queryMysql($query)) == 0) {
$error = "Username/Password invalid<br />";
} else {
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
$str = $_SESSION['user'] . ", You are now logged in. Please
<a href='scheduler.php'>click here</a>.";
die($str);
}
}
} ?>
It'll print the correct store name after the query and all that. But when I try to use it in another php file like this
if (!isset($_SESSION['user']) ) {
die("<p><h1>Please Login</h1></p>");
} else {
echo "<p><form id ='addemp' method=\"post\" action=\"addUser.php\">
Name<input type=\"text\" name=\"emp\" />
\"". $_SESSION['user'] . "\">
<input type=\"submit\" value=\"AddUser\" />
</form></p>";
}
It is an empty string. Not null just empty string. I tried all the solutions I can find on the internet, none of them worked. I'm out ideas as to why this isn't working.
Any help will be greatly appreciated, thank you.
It could be a number of things. First of all do sessions work any other time?
I don't think you have provided enough information for us to help you. It could be a problem with set-up of apache/php not just your code. Has happened to me before when I was developing on Windows with WAMP and temp folder didn't have correct permissions. As I said there could be many issues that cause your session to misbehave.
When you do a counter and refresh
page does it keep a number?
At the
beginning of every time that uses sessions you need to have
session_start() method called.
Important: There can't be any echo's or prints etc before
session_start().
Put var_dump($user) before $_SESSION['user'] = $user; and check the content of $user before it gets saved. It could be that your sanitizing function is not working properly. Do it also at the end of the first script to see the content of $_SESSION to make sure variables are saved properly.
You need to call session_start() before using $_SESSION. Also note that keeping the password in the session is a very BAD practice and a BIG security hole.
If you claim to have inserted session_start() in that page too, do 2 things:
1) correct your html, this line.
echo "<p><form id ='addemp' method=\"post\" action=\"addUser.php\">
Name<input type=\"text\" name=\"emp\" />
\"". $_SESSION['user'] . "\">
Has something not really clear. Where do you echo your $_SESSION to? is it maybe that your browser fails at rendering it? What did you want to accomplish? It can be that the browser is interpreting wrong that closing tag >. Try tidying html first.
If that was meant to be the input field value, write
Name <input type=\"text\" name=\"emp\" value=\"".$_SESSION['user']."\"/>
2) var_dump the $_SESSION['user'] to see if it's really an empty string.
if (!isset($_SESSION['user']) ) {
die("<p><h1>Please Login</h1></p>");
} else {
var_dump($_SESSION['user']);
}
It sounds like the OP had an issue with register_globals.
In php.ini set register_globals = Off, then try the code again.
I had the exact same problem - I had a user variable in the session, and then set $user = array(); and found that the $user variable was overwriting the $_SESSION['user'] variable. Disabling register_globals fixed it.
Or you can change your $user variable to something like $myUser, but it's better to disable register_globals anyway.
Based on #kpaulsen answer,
I got same situation on him, $variable overwrites $_SESSION['variable'] so I followed his suggestion but it isn't works fine on me then I found out another way of setting the register_globals = Off
Add this line on .htaccess
php_flag register_globals off
Maybe its a issue I had some time ago, made all the code perfectly, but forgot to insert the session_start(); at the connection script, witch receives the log-in $_POST['somevariable'] to validate with the DB.
On resume, don’t forget to start a session at your connection.

Categories