Storing data from query in $_SESSION - php

I've looked everywhere but most solutions are outdated or confusing.
After a user's email and passwords match, their name and id are also saved then they are sent to their homepage.
<?php
session_start();
$con=mysqli_connect("localhost", "root", "", "projectinnovations");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL:" . mysqli_connect_errno();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$email = stripslashes($email);
$password = stripslashes($password);
$sql="SELECT * FROM individual_users WHERE email='$email' and password='$password'";
$result=mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if ($count==1)
{
$_SESSION['email']= $email;
$_SESSION['password']= $password;
$sql1="SELECT fullname FROM individual_users WHERE email='$email' and password='$password'";
$result1=mysqli_query($con,$sql1);
$_SESSION['fullname']= mysqli_fetch($result1);
$sql2="SELECT id FROM individual_users WHERE email='$email' and password='$password'";
$result2=mysqli_query($con,$sql2);
$_SESSION['id']= mysqli_fetch($result2);
header("location:home.php");
}
else
{
header("location:login.php");
}
}
mysqli_close($con);
?>

In order to make dealing with the session possible add session_start(); to the top of your script.

You haven't started the session
The simple answer is that you need to put session_start() at the top of the script (and the top of any script that uses the session variables).
But really, you don't need to do this...
The better answer is that what you're doing looks dangerously like relying on globals, and there's no reason to keep things like user e-mail addresses as global variables. Consider taking another look at your application architecture to see why you need to do this.
What could you do instead?
You'd be better off creating a User class which has the variables you need, then creating an instance of that class whenever you need access to user data.
If your worry is database congestion, look into memcached or APCu to lighten the load.
Other issues
If this is real code, you should be using password_hash and password_verify to handle login. Currently, you are storing passwords in plaintext, free for any hacker to look at.
You should also look into binding parameters in queries, which would allow you to avoid having to think about escaping values before running queries.

Related

Why my login form allowing users to login with correct USERNAME, but incorrect PASSWORD? (See detail)

I've made a login form using PHP and MySQL. Now the problem is that when I enter correct username and password, it logins, but when I enter correct username and correct "password+ANY_OTHER_CHARACTER", it still logins. Why is it happening?
For example: If the username and password stored in database are:
Username: username1
Password: 1213456
Then if I enter these credentials in login form, it logs me in.
But if I try following credentials:
Username: username1
Password: 1213456asdfjksdj
It still logs me INTO SAME account.
Why is it happening?
One more thing, it was working fine previously, but I've used some seesion variables and session_start() functions. I think the problem started after using session. Please help.
My login PHP code is:
<?php
session_start();
if(isset($_SESSION["cur_user_sess"]) && isset($_SESSION["cur_user_pass"]))
{
header("Location: welcomehome.php");
}
?>
<?php
$a=mysqli_connect('localhost', 'root','', 'onlinequiz');
if(isset ($_REQUEST['signup']))
{
$c=$_REQUEST['uname'];
$d=$_REQUEST['email'];
$e=$_REQUEST['phone'];
$f=$_REQUEST['pass'];
$h="INSERT INTO signup(Name, Email, Phone, Password) VALUES ('$c', '$d', '$e', '$f')";
$i= mysqli_query($a,$h);
if($i)
{
header("Location: login2.php");
}
else
{
echo "error";
}
}
?>
<?php
$a=mysqli_connect('localhost','root','', 'onlinequiz');
if (isset ($_REQUEST['login']))
{
$c=$_POST['mail'];
$d=$_POST['pass'];
$e="SELECT * FROM signup WHERE Email='$c' and Password='$d'";
$f=mysqli_query($a,$e);
if(mysqli_num_rows($f)==1)
{
$_SESSION["cur_user_sess"]=$c;
$_SESSION["cur_user_pass"]=$d;
header ("Location: welcomehome.php");
}
else
{
$error2 = "Enter correct information";
}
}
?>
<?php
$mysql=mysqli_connect('localhost','root','','onlinequiz');
$currentuser=$_SESSION["cur_user_sess"];
$sql = "SELECT * FROM signup WHERE Email='$currentuser'";
$result = mysqli_query($mysql, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION["profilename"]=$row["Name"];
//$_SESSION["profilepoints"]=$row["Points"];
$_SESSION["profilephone"]=$row["Phone"];
?>
Do you destroy the session or unset the curr_user_sess and curr_user_pass?
<?php
session_destroy(); // Is Used To Destroy All Sessions
//Or
if(isset($_SESSION['curr_user_sess']))
unset($_SESSION['curr_user_sess']); //Is Used To Destroy Specified Session
if(isset($_SESSION['curr_user_pass']))
unset($_SESSION['curr_user_pass']);
?>
Do this when logging out. If you don't, the session will stay set after you correctly login and you don't even get to the part where it checks the email and password you provided.
First, a few pointers.
$a, $b, $c? Stop doing that! Proper naming conventions! Your SQL query chould be "$query" for example, your MYSQLI connection could be "$dbh" or "$connection", etc. This makes code far easier to read through.
Second, you're dropping "unsanitized" values straight into a SQL query. Why is this bad? Because if someone enters the username 1' or '1' = '1, they've just found out they can waltz into your entire system.
Passwords? Plaintext? You really want to encrypt that! Here's a little article that will get you going in the right direction.
Next, using $_REQUEST is generally a bad idea for 2 reasons. First, basic security, and second? Code maintenance. Instead break it down into $_POST and $_GET so that it at least identifies your data source.
Last but not least, try looking at this tutorial for PHP PDO. It's a far better way of handling DB interaction than Mysqli. More secure and less confusing, too.
Try this instead of your existing test login and let me know if it works.
$mysqli = new mysqli("localhost", "user", "pass", "db");
# Basic data sanitization
$pass = mysqli_real_escape_string($_POST['email']);
$mail = mysqli_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM signup "
. "WHERE Email = '$mail' AND password = '$pass'";
$result = $mysqli->query($sql);
if($result->num_rows == 1) {
echo "Logged in";
} else {
echo "Failed to sign in";
}

Need help regarding a PHP/SQL login function

Before you say it: I know the passwords should be encrypted/hashed, but I want to get this down first:
I have this login function and a SQL database. However, the login function doesn't seem to work and I haven't the faintest idea why. I am probably missing something stupid, but have been struggling with this for a while now. Any help would be appreciated!
NOTE: the file db_connect.php is really just a basic connecting to the database, nothing wrong there
FUNCTION.PHP:
<?
function login($username, $password, $con)
{
$myQuery = "SELECT * FROM Members WHERE Username = '$username' and Password = '$password';";
$result = mysqli_query($con, $myQuery);
if (mysql_num_rows($result) == 0)
{
return false;
}
else
{
return true;
}
}
?>
PROCESS-LOGIN.PHP:
<?php
include 'db_connect.php';
include 'functions.php';
if (isset($_POST['username'], $_POST['pword'])) {
$username = $_POST['username'];
$password = $_POST['pword']; // The hashed password.
if (login($username, $password) == true) {
// Login success
header('Location: welcome.html');
}
else
{
// Login failed
header('Location: index.html');
}
}
else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
You are not providing the $con parameter to login function.
function login($username, $password, $con)
You are calling it as
login($username, $password)
Try providing the connection argument to see if it works.
Also note the answer kingkero made. You are using functions from different libraries.
Some things I noticed
Are you using method="POST" in your form?
Your SQL query is vulnerable to SQL injections
your mixing mysql_* with mysqli_* functions
missing $con parameter for login function
You are mixing MySQLi (mysqli_query) with MySQL (mysql_num_rows) - decide for either one (preferably the former).
If you are using MySQL, the parameters for mysql_query are in wrong order.
In addition to that you are failing to pass the connection to the login as a parameter (as WoLfulus mentioned).
Some additional info as you seem to be learning:
The return statement of login can be simplified to return mysql_num_rows($result) == 1;. This will return TRUE if one record was found and FALSE otherwise - no need for an if/else statement here, you already have the logic you need.
Right now anyone can access welcome.html without logging in by simply typing the address in the browser. This can be avoided by using sessions.
Since you don't properly escape the user input (which one should never trust!), you are vulnerable to SQL injections. mysql_real_escape_string is a start but no 100% solution. If you used prepared statements on the other hand, you wouldn't need to worry.
I'm answering since I don't have enough reputation to comment your question.. But you should keep your variables outside the quotes and add mysql_real_escape_string() to prevent mysql injection..
$myQuery = "SELECT * FROM Members WHERE Username = '$username' and Password = '$password';";
Should be:
$myQuery = "SELECT * FROM Members WHERE Username = '". mysql_real_escape_string($username) ."' and Password = '". mysql_real_escape_string($password) ."';";

How to adapt my PHP Session into an Array

I have this PHP code which I'm using to trigger the user log in. For a successful log in, the user uses their registered email and password. My current PHP code allows the username to be echoed on whatever pages use the $_SESSION['loggedin'] = $dbusername. What I'm now trying to do is to adapt this PHP code to put an Array into the 'loggedin' session. I want the array to hold user registration details i.e firstname, lastname, company and email, aswell as their username (dbusername). This is to enable me to echo such details on a 'user account page'
My code:
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
if ($email&&$password)
{
$connect = mysql_connect("*****","***","**********") or die ("Login failed!");
mysql_select_db("dbname") or die ("Could not connect to Database");
$query = mysql_query("SELECT * FROM regusers WHERE email='$email'");
$numrows = mysql_num_rows($query);
if($numrows !=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbemail = $row['email'];
$dbpassword = $row['password'];
$dbusername = $row['username'];
}
if ($email==$dbemail&&$password==$dbpassword)
{
include 'loginIntro.php';
$_SESSION['loggedin']=$dbusername;
}
else
echo "Incorrect Password";
}
else
die ("That email doesn't exist");
}
else
die ("Enter a registered email and password");
?>
Then on my 'user account page' I have this :
<?php
session_start();
$dbusername = $_SESSION['loggedin'];
?>
For the purposes of echoing the username this PHP code works fine, as all I have to do is : any time I want to display the users username. So going back to my original question - Please impart the necessary knowledge to adapt this PHP code to hold the users registration details so I can echo such details on whatever page(s) use the session in question. Please forgive my lack of knowledge and understanding, I've scratched my head so hard I've got cradle cap - which only babies get, but in this PHP game I'm an embryo. Thanks for whatever help comes
$_SESSION is a array
You can simply save a associative array inside of it.
$_SESSION['id'] = $x;
$_SESSION['username'] = $y;
$_SESSION['realname'] = $z;
or a nested array
$_SESSION['user']['id'] = $x;
$_SESSION['user']['username'] = $y;
$_SESSION['user']['realname'] = $z;
Beware
You are using deprecated functions.
There is no validation on data passed.
There is a risk (looks like 100%) of SQL injection.
As bwoebi said, you may not save password in clear text.
Suggested reading
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/session.examples.basic.php
http://php.net/manual/en/filter.examples.validation.php
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/intro.pdo.php
If you want to use an Array as a Session variable, you have to serialize it first. (http://php.net/manual/en/function.serialize.php).
Then you can add it to $_SESSION, and unserialize (http://php.net/manual/en/function.unserialize.php) it on the other pages.
Now here are two advices : hash your passwords using sha1 (http://us2.php.net/manual/en/function.sha1.php), and don't use mysql_* functions, which are outdated. Consider using mysqli ou PDO.

Login systems with php and mysql

When a user logs in, how do I get all of their mysql information? I have a registering system and login system. When they log in they type their username and password, those are the only two variables i can use, because they type them in. How do I get all the other variables, not typed in by the user, for that profile?
Their usernames are unique. How do i get the rest of their variables to use throughout all of my php files?
My login file:
<?
/*Use of Sessions*/
if(!session_id())
session_start();
header("Cache-control: private"); //avoid an IE6 bug (keep this line on top of the page)
$login='NO data sent';
/*simple checking of the data*/
if(isset($_POST['login']) && isset($_POST['pass']))
{
/*Connection to database logindb using your login name and password*/
$db=mysql_connect('localhost','teachert_users','dogs1324') or die(mysql_error());
mysql_select_db('teachert_users');
/*additional data checking and striping*/
$_POST['login']=mysql_real_escape_string(strip_tags(trim($_POST['login'])));
$_POST['pass']=mysql_real_escape_string(strip_tags(trim($_POST['pass'])));
$_POST['pass']=md5($_POST['pass']);
$_POST['pass']=strrev($_POST['pass']);
$_POST['pass']=md5($_POST['pass']);
$_POST['pass'].=$_POST['pass'];
$_POST['pass']=md5($_POST['pass']);
$q=mysql_query("SELECT * FROM profiles WHERE username='{$_POST['login']}' AND password='{$_POST['pass']}'",$db) or die(mysql_error());
/*If there is a matching row*/
if(mysql_num_rows($q) > 0)
{
$_SESSION['login'] = $_POST['login'];
$login='Welcome back, '.$_SESSION['login'];
$login.='</br> we are redirecting you.';
echo $login;
echo '<META HTTP-EQUIV="Refresh" Content="2; URL=/php/learn/selectone.php">';
exit;
}
else
{
$login= 'Wrong login or password';
}
mysql_close($db);
}
//you may echo the data anywhere in the file
echo $login;
?>
I can use their login and password in all other files with the $_SESSION['var'];
How do i get the rest? Like their age? or their Name? or any variable stored in my mysql files.
Yes i know MD5 isn't the best, let's not turn this into a discussion on that.
------------------------edit-------------------------------
I guess i'll rephrase that:
I use this:
$q=mysql_query("SELECT * FROM profiles WHERE username='{$_POST['login']}' AND password='{$_POST['pass']}'",$db) or die(mysql_error());
How do i get variables from that particular user/profile. Like their other variables, such as their name, which in my mysql is fname.
-------------------------Edit---------------------------
I have updated to:
$mysqli = new mysqli('localhost', 'teachert_users', 'dogs1324', 'teachert_users');
if($mysqli->connect_errno) {
echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$user = $_SESSION['login'];
$get_user_info_query = $mysqli->query("SELECT * FROM profiles WHERE username = '$user'");
if($get_user_info_query->num_rows) {
while($get_user_info_row = $get_user_info_query->fetch_assoc()){
if ($get_user_info_row['math']) {
print_r($get_user_info_row['math']);
}
}
} else {
echo 'User not found';
}
but the print_r still prints all of the user's information. not just the math information. Why?
please try using mysqli or pdo, mysql_* functions are oficially deprecated
$mysqli = new mysqli($dbserver, $dbmanager, $dbpass, $dbname);
if($mysqli->connect_errno) {
echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
$user = $_SESSION['login'];
$get_user_info_query = $mysqli->query("SELECT * FROM profiles WHERE username = '$user'");
if($get_user_info_query->num_rows) {
while($get_user_info_row = $get_user_info_query->fetch_assoc()){
print_r($get_user_info_row);
}
} else {
echo 'User not found';
}
this will print the entire row information returned by mysql so to use one specific field use $get_user_info_row['username'] inside the while statement.
This is the code to get data information using the mysql_ approach:
$row = mysql_fetch_assoc($q);
The variable $row will have an array with the fields returned by the sql statement. Use this line after check if the exist rows.
Try to run
print_r($row)
and you will see it contents.
First, custom encryption routines are not considered secure, especially if you post your code (or a variant of it) here.
Second, your routine has no extra security over a plain MD5 (which is considered horribly insecure). Let's say your routine takes 3x longer than a plan MD5. Big deal, you can do a billion MD5s per second, so at best you've added a few seconds to the attacker's cracking time when trying the 1 billion most common passwords.
You should never try to roll your own password routines. In fact, you shouldn't be rolling your own user login and session code either. Use a framework like CakePHP. (You may need a plugin for the User Auth stuff. Make sure it uses bcrypt().)
When you use a framework, you will benifit from having lots of pre-existing examples and "best practices". You'll be programming at a higher level. In fact, frameworks often provide protection against attacks you don't even know about, like SQL injection, XSS, etc.

How to echo out info from MySQL table in PHP when sessions are being used.

I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).

Categories