How to adapt my PHP Session into an Array - php

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.

Related

Storing data from query in $_SESSION

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.

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";
}

Unable to check for password and username at login

I have tried to create a PHP log in form. My code is as follows. The if-else statement is not functioning well. Please solve this.
$connect = mysql_connect("localhost", "root", ""); //connect
mysql_select_db("elective_mgmt", $connect);
$username = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * from verify_student where
username='$username' && password='$password'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (name == $username && password == $password)
echo "you are logged in";
else
echo "please recheck your password and username";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "you are logged in";
}
else
echo "please recheck your password and username";
You can also do this by counting the number of rows. In your code $row is an array so whenver you need to acces the array elements do this $row['name']
You have a problem here.
if(name==$username && password==$password)
It should be
if($row['name']==$username && $row['password']==$password)
OR
if(mysql_num_rows($result) == 1)
You should look at - Why shouldn't I use mysql_* functions in PHP?
You could remove your if/else statement since you check the inputs already with your mysql query (name && password) and replace it with a mysql_num_rows == 1 (as the others have already mentioned before).
It seems that you are new to php and creating log in forms, so let me give you a good advice:
input values for a log in form shouldn't be passed via URL, use method post instead
never save passwords unencrypted (use sha512 since md5 is considered unsafe)
never use single information to store the log in status in the session

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).

How do I authenticate a user in PHP / MySQL?

So recently I learned how to properly add a username and password to a database.
My database is usersys, and the table storing user information is called userdb. The table has two columns - username (primary), password.
The registration form works great, enters the users input into the database correctly and also checks to see whether the user's username is already in the database or not.
With that said, I am asking if anyone could help me create a login script. So far, this is what I have:
$username = $_POST['username'];
$password = $_POST['password'];
$displayname = $_POST['username'];
$displayname = strtolower($displayname);
$displayname = ucfirst($displayname);
echo "Your username: " . $displayname . "<br />";
mysql_connect("localhost", "root", "******") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("usersys") or die(mysql_error());
echo "Connected to Database <br />";
$lcusername = strtolower($username);
$esclcusername = mysql_real_escape_string($lcusername);
$escpassword = mysql_real_escape_string($password);
$result = mysql_query("SELECT * FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$validateUser = $row['username'];
$validatePass = $row['password'];
The POST data is from the previous log in page. I want this script to check the table (userdb) and find the row for the username that the user entered from the previous form and verify that the password entered matches the username's password set in that row, in userdb table.
I also want some type of way to check whether or not if the username entered exists, to tell the user that the username entered does not exists if it can not be found in the table.
This is not a direct answer to this question but a GOOD value-add.
You should use MYSQL SHA1 function to encrypt the password before storing into the database.
$user = $_POST['userid'];
$pwd = $_POST['password'];
$insert_sql = "INSERT into USER(userid, password) VALUES($user, SHA1($pwd))";
$select_sql = "SELECT * FROM USER WHERE userid=$user AND password=SHA1($pwd))";
You can use sessions. Sessions are global variables that when set, stay with the user while he is browsing through the site.
Since you are learning PHP, try out this tutorial on the official website.
But what you would do in theory is when the username and password match, you set a session variable
$_SESSION["auth"] = true;
$_SESSION["user_id"] = $row["user_id"];
And then do a check to see if the user is authenticated.
One way to do it (DISCLAIMER: not necessarily best-practice):
$result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$id = (int)$row['id'];
if($id > 0) {
//log in the user
session_start();
$_SESSION['userId'] = $id;
$_SESSION['username'] = $displayname;
}
... and on pages that require authentication:
session_start();
if(!isset($_SESSION['userId'])) {
die('You need to be logged in!!!');
} else {
echo 'Welcome ' . $_SESSION['username'];
}
Read more about PHP sessions.
I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.
$username = mysql_real_escape_string($_POST[username]);
$password = strip_tags($_POST[password]);
$password = sha1($password);
if(isset($username) && isset($password) && !empty($username) && !empty($password))
{
$sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
//Check the number of users against database
//with the given criteria. We're looking for 1 so
//adding > 0 (greater than zero does the trick).
$num_rows = mysql_num_rows($sql);
if($num_rows > 0){
//Lets grab and create a variable from the DB to register
//the user's session with.
$gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
$row = mysql_fetch_assoc($gid);
$uid = $row[userid];
// This is where we register the session.
$_SESSION[valid_user] = $uid;
//Send the user to the member page. The userid is what the
//session include runs against.
header('Location: memberpage.php?userid='.$userid);
}
//If it doesn't check out -- throw an error.
else
{
echo 'Invalid Login Information';
}
}
NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.
You could use a select statement to retreive from MySQL the password for the specified username. If you have an empty result set, then you do not have the username in the table.
If you need the user to be authenticated in more than one php page, then one choice whould be using sessions (http://www.php.net/manual/en/function.session-start.php).
Also, I think you should think about security, i.e. preventing SQL injection:
$variable = mysql_real_escape_string($_POST['variable'])
and avoiding to "die" (treating errors and returning user-friendly messages from the script).
I would also think about not storing passwords in your database. One way hashes with MD5 or SHA1 are a way of adding a layer of security at the db level.
See http://php.net/md5 or http://php.net/sha1 for further information.
I agree with the idea if using SESSION variables while authenticating the user.
The easy way to authenticate the user is as follows
//connect the mysql_db
$mysql_connect()
$mysql_select_db()
//reading from mysql table
$res="SELECT * FROM table WHERE name=$username AND password=$password";
$val=mysql_query($res);
//authentication
$count=mysql_num_rows($val);
if($count==1)
//authenticate the user
else
through an error

Categories