How to show other columns in php session - php

I am trying to extract other user info when I log in. I have managed to enable myself to login using my email address and password but I am struggling to show my first/last name etc.
I am logging in like so:
$query = "SELECT * FROM users WHERE user_email = '". $email ."' AND user_password = '". $password ."'" ;
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 1) {
$_SESSION['user_email'] = $email;
header('Location: dashboard.php');
} else {
echo 'fail!';
}
Then in my header I have:
session_start();
if( !isset($_SESSION['user_email']) ){
header('Location: index.php');
exit();
} else{
$email = $_SESSION['user_email'];
echo 'Logged in';
}
But fi I try to echo out user_firstname or user_lastname it fails of course I am just not sure where this gets set?

You need to use read a row from the query, then set session variables from that.
if (mysqli_num_rows($result) == 1) {
$_SESSION['user_email'] = $email;
$row = mysqli_fetch_assoc($result);
$_SESSION['user_firstname'] = $row['user_firstname'];
$_SESSION['user_lastname'] = $row['user_lastname'];
header('Location: dashboard.php');
} else {
echo 'fail!';
}
You can print the session variables in the header.
session_start();
if( !isset($_SESSION['user_email']) ){
header('Location: index.php');
exit();
} else{
$email = $_SESSION['user_email'];
echo 'Hello, ' . $_SESSION['user_firstname'];
}
You could also just put the entire row into the session:
$_SESSION['user_data'] = $row;
Then you can use $_SESSION['user_data']['user_firstname'] to get specific fields.

Related

Change text upon redirect from certain page...?

As the title suggests I am trying to use the same .php page and have it display something new upon being redirected from a particular location.
In context...
I have a login which upon successful login redirects to a home page but if unsuccessful, redirects to the index. Is there a way that I can tell my index page to display an "Error logging in" message when it has been redirected from my login page?
Here is my login code...
<?php
session_start();
include('conn.php');
$query = "SELECT * FROM User";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (isset($_POST["submit"])) {
$logEmail = $conn->real_escape_string($_POST['logEmail']);
$logPass = $conn->real_escape_string($_POST['logPass']);
$checkuser = "SELECT * FROM User WHERE Email='$logEmail' AND UserPassword=AES_ENCRYPT('$logPass', 'MyKey')";
$userresult = mysqli_query($conn, $checkuser) or die(mysqli_error($conn));
$loginsucc = (mysqli_num_rows($userresult) > 0);
if (mysqli_num_rows($userresult) > 0) {
while ($row = mysqli_fetch_assoc($userresult)) {
$userPriKey = $row['UserID'];
$userid = $row['Email'];
$accounttype = $row['IsAdmin'];
$firstname = $row['FirstName'];
$surname = $row['LastName'];
$_SESSION['userPriKey'] = $userPriKey;
$_SESSION['name'] = $firstname;
$_SESSION['surname'] = $surname;
$_SESSION['Email'] = $userid;
$_SESSION['IsAdmin'] = $accounttype;
if($accounttype == '1'){
header("Location: home.php");
}else if ($accounttype == '0'||$accounttype == NULL ) {
header("Location: userhome.php");
}
}
} else {
header("Location: index.php");
}
}
?>
Before you call header() set a session variable like so
$_SESSION['msg'] = 'success you are logged in';
header('Location: page.php');
exit;
Then in page.php,
session_start();
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Also FYI, you should be using prepared statements. Your code is not totally safe

PHP Log in page with hashed password issue

So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.
<?php
session_start();
include 'databaseconnection.php';
$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);
$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);
if ($hash == 0) {
header("Location: error.php")
exit();
} else {
$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);
if (!row = mysqli_fetch_assoc($result)); {
echo "your email address or password is incorrect!";
} else {
$_SESSION['id'] = $row['id'];
}
header("Location: profile.php")
If someone could simply suggest what changes I should make, I would really appreciate it.
There you go simple code
<?php
session_start();
include 'databaseconnection.php';
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database
// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
$_SESSION['id'] = $row['id'];
header('Location: profile.php');
}
else
{
header("Location: error.php")
exit();
}
?>
You have not closed the "} else {"... section.
First check request second filter input third use pdo
<?php
session_start();
include 'databaseconnection.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
$pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
$hashed = sha1($pwd);
$sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
$sql->execute(array($email, $pwd));
$row = $sql->fetch();
if($row['email'] !== $email || $row['password'] !== $hashed){
header("Location: error.php");
exit();
} else {
$_SESSION['id'] = $row['id'];
header("Location: profile.php");
}
}else {
echo 'error';
}
?>

pulling more data from a table using a session(I want to display a user's data in profile format)

I am struggling to display a user's profile after logging in. I can only display the user email in the session.
below is my login script
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($db , $_POST['email']);
$password = mysqli_real_escape_string($db , $_POST['password']);
$query = "select * from users where email='$email' and password='$password'";
$result = $db->query($query);
if($row = $result->fetch_assoc()){
if($row['status'] == 1){
$_SESSION['user_email'] = $email;
if(isset($_POST['remember_me'])){
setcookie("user_email" , $email , time()+60*5);
}
header("Location:myaccount.php");
exit();
}else {
header("Location:index.php?err=" . urlencode("The user account is not activated!"));
exit();
}
} else {
header("Location:index.php?err=" . urlencode("Wrong Email or Password!"));
exit();
}
}
After the user logins, they get redirected to this page "myaccount.php"
This displays only the user email only, I need to pull more user data from the table.
You can set any data to session
like this
$_SESSION['username'] = $row['username'] ;
$_SESSION['name'] = $row['name'] ;
$_SESSION['family'] = $row['family'] ;
so
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$query = "select * from users where email='$email' and password='$password'";
$result = $db - > query($query);
if ($row = $result - > fetch_assoc()) {
if ($row['status'] == 1) {
$_SESSION['user_email'] = $email;
$_SESSION['name'] = $row['name'];
$_SESSION['family'] = $row['family'];
if (isset($_POST['remember_me'])) {
setcookie("user_email", $email, time() + 60 * 5);
}
header("Location:myaccount.php");
exit();
} else {
header("Location:index.php?err=".urlencode("The user account is not activated!"));
exit();
}
} else {
header("Location:index.php?err=".urlencode("Wrong Email or Password!"));
exit();
}
}

Validating a login and creating sessions using PHP

Trying to validate a login in PHP but not quite getting the hang of it. The problem with this code is that even if the login is not valid and does not match the data in the database, it will still log them in. The redirect code at the bottom works fine. Any ideas?
CODE:
$result = mysql_query("SELECT * FROM user WHERE username='" . $_POST["username"] . "' and password = '" . $_POST["password"] . "'");
$row = mysql_fetch_array($result);
if (is_array($row)) {
$_SESSION["user_id"] = $row[user_id];
$_SESSION["user_name"] = $row[username];
} else {
echo = "Invalid Username or Password!";
}
if ($_SESSION["user_name"] == 'ADMIN') {
header("Location: admin.php");
} else {
header("Location: useroptions.php");
}
$result = mysql_query("SELECT * FROM user WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["user_id"] = $row[user_id];
$_SESSION["user_name"] = $row[username];
if($_SESSION["user_name"] == 'ADMIN'){
header("Location: admin.php");
} else {
header("Location: useroptions.php");
}
} else {
echo "Invalid Username or Password!";
}
Looks like you might have some logic issues, try this:
<?php
session_start();
$sql = "SELECT * FROM user WHERE username='" . $_POST["username"] . "' and password = '" . $_POST["password"] . "'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if($count === 1)
{
$row = mysql_fetch_assoc($query);
$_SESSION["user_id"] = $row[user_id];
$_SESSION["user_name"] = $row[username];
if($_SESSION["user_name"] == 'ADMIN')
{
header("Location: admin.php");
}
else
{
header("Location: useroptions.php");
}
}
else
{
echo = "Invalid Username or Password!";
}
?>
I highly recommend looking into using a PDO connection because it will be much more portable and parameterized queries pretty much eliminate security issues if used properly.
All mysql_* functions are going to be deprecated as well so you should invest your time in learning the newest standards. A mechanic is not going to focus on learning carborated engines, they are going to focus on fuel-injection systems.
The big red sign is a sign to stop using these functions:
Try this
$result = mysql_query("SELECT * FROM user WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["user_id"] = $row[user_id];
$_SESSION["user_name"] = $row[username];
}
else {
echo "Invalid Username or Password!";
exit();
}
if($_SESSION["user_name"] == 'ADMIN'){
header("Location: admin.php");
exit();
}
else {
header("Location: useroptions.php");
exit();
}
Now your login will valid your data is not match with database because your have a little space username='" . $_POST["username"]. "' and password = '".$_POST["password"]."'
Now try it........
$result = mysql_query("SELECT * FROM user WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["user_id"] = $row[user_id];
$_SESSION["user_name"] = $row[username];
}
else {
$message = "Invalid Username or Password!";
}
if($_SESSION["user_name"] == 'ADMIN'){
header("Location: admin.php");
}
else {
header("Location: useroptions.php");
}

Login page and profile page redirection the system do not display the right page

I have a login page that allow user to submit a registered email and password and if the data is correct then the system redirect to the profile page and here i face the problem .
when I try to submit the write data the system do not redirect me to the profile page .
but if I echo a confirm message that the data are correct the browser display this message
how to fixx this problem ???
login.php
<?php
session_start();
error_reporting(E_ALL);
require_once('include/connect.php');
$message = "";
if(!empty($_POST['email']))
{
$email = $_POST['email'];
$pass = $_POST['pass'];
$email = strip_tags($email);
$pass = strip_tags($pass);
$email = mysql_real_escape_string($email);
$pass = mysql_real_escape_string($pass);
//$pass = md5($pass);
$sql=mysql_query( "SELECT user_id, email_address, first_name FROM user WHERE email_address='$email'AND password='$pass'LIMIT 1") or die("error in user table");
$login_check = mysql_num_rows($sql);
if($login_check > 0)
{
$row = mysql_fetch_array($sql);
$id = $row['user_id'];
$_SESSION['user_id'] = $id;
$firstname = $row['first_name'];
$_SESSION['first_name']= $firstname;
$email = $row['email_address'];
$_SESSION['email_address']= $email;
mysql_query("UPDATE user SET last_log_date=now() WHERE user_id='$id'");
//$message = "correct email and passworddd!!";
header("Location: profile.php");
}//close if
else
{
$message = "incorrect Email or Password!!";
//exit();
}
}//close if
?>
profile.php
<?php
session_start();
require_once('include/connect.php');
if(isset($_GET['user_id']))
{
$id=$_GET['user_id'];
var_dump($id);
}
elseif(isset($_SESSION['user_id']))
{
$id= $_SESSION['user_id'];
}
else
{
print "Important data are missing";
print_r($_SESSION);
exit();
}
$sql = mysql_query("SELECT * FROM user WHERE user_id='$id'") or die(mysql_error());
$row = mysql_fetch_array($sql);
$firstname=$row['first_name'];
$lastname=$row['last_name'];
$birth_date=$row['birth_date'];
$registered_date=$row['registered_date'];
//***************for upload img*****************//
$check_pic="members/$id/image01.jpg";
$default_pic="members/0/image01.jpg";
if(file_exists($check_pic))
{
$user_pic="<img src=\"$check_pic\"width=\"100px\"/>";
}
else
{
$user_pic="<img src=\"$default_pic\">";
}
echo $id, $firstname, $birth_date;
?>
Easy :) Just put all this code on the top of content and be sure that there is no any content on the page where header("Location: profile.php"); is working, because if there is something it can't be loaded. I also recommend to use exit; after header("Location: profile.php");

Categories