Session is not kept/destroyed when i navigate to other pages - php

Good day.SO i am having an issue in that, when i create a session via a login and a user is authenticated, once i leave that page to say a different page, i am not whether the session is destroyed or not created in the first place, i require this page to hold the session so i can be able to query the users email from it, and use it to query the database to determine the username.
This is my submit.php, called once the user clicks login on the page.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =$_POST['password'];
$sql = "SELECT * FROM `USERS` WHERE EMAIL='$email' AND ENCRYPTEDPWD='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['email'] = $email;
header("Location: Landing page.php");
exit();
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
?>
it redirects to the next page, the landing page.
This page should check email from the session, and then display a username.
<?php
session_start();
$_SESSION['email'] = $email;
$sql = "SELECT * FROM users WHERE EMAIL='$email';";
$result = mysqli_query($connection,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row['username'];
}
}
else{
echo "No User.";
}
?>
Please help.

You have an issue with the landing page in below line:-
$_SESSION['email'] = $email;// here you are assigning to SESSION
It needs to be:-
$email = $_SESSION['email'];//assign value from SESSION to variable
So code needs to be like this:-
$email = $_SESSION['email'];
$sql = "SELECT * FROM users WHERE EMAIL='$email'";
Note:- Your code is wide-open for SQL INJECTION. Try to use prepared statements to prevent it.
mysqli::prepare

In your landing page, invert the line after session_start(): You are assigning an empty variable to overwrite your already saved session variable
$email = $_SESSION['email'];
If your query causes you problems after that, try concatenating $email
$sql = "SELECT * FROM users WHERE EMAIL='".$email."';";

Related

PHP landing page based on user type

I`m trying to set the login.php page to divert the user after successful login to different landing page. For instace, if type = model, location:model-dashboard.php or if type=photographer, location:photographer-dashboard.php. At the moment, all users goes to dashboard.php
here is my current php code, for which i`m happy to take any suggestions
if(loggedIn()){
header("Location:dashboard.php");
exit();
}
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:dashboard.php");
exit();
}else {
header("Location:login.php?err=" . urlencode("Contul nu este activat"));
exit();
}
}else {
header("Location:login.php?err=" . urlencode("E-mail sau parola gresita"));
exit();
}
}
i already tried:
$query = "select * from users where email='$email' and password='$password' and type='$type'";
and then
if($type =='model'){
$link = 'model-dashboard.php';
}
elseif($type =='photographer'){
$link ='photographer-dashboard.php';
}
and use Location:$link bot no joy
Edited: $type = $row['type']; already defined this, just forgot to mention it
the current code is the one that works with single page, so just need to know what should i remove and add instead.
thank you in advance!
You say you tried adding an AND condition to your query. However, you don't want to constrain the users, you want to get the type from the user. Instead of adding an AND, get the type from the row:
$type = $row['type'];
// Determine $link using $type
Also, note that your current approach of redirecting users to login.php with an error is vulnerable to reflective XSS.

i am Unable to fetch the user id of logged in user from my data base

I am using PHP to get the user id to display the profile details of logged in user but i am unable to fetch the id Here is my code in login page
$email = mysqli_real_escape_string($con,$_POST['email']);
$q = "select * from users where email = '$email'";
$rows=mysql_fetch_assoc($q);
$id = $rows['$id'];
$result = mysqli_query($con, $q);
$num = mysqli_num_rows($result);
if($num == 1){
$_SESSION['user'] = $email;
header("location:home.php?id=$id");
}else{
$reg = "insert into users(email) values ('$email')";
mysqli_query($con, $reg);
header('location:index.php?msg');
}
Here is my home page code
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location:index.php");
exit;
}
$id = $_REQUEST['id'];
include_once('conn.php');
$query="select * from users WHERE id= '$id' ";
$result=mysql_query($query);
?>
Looks like you appended the $id from your login page to home.php?id=$id and then in your home.php file, you are trying to fetch that $_GET['id'] value.
Here are the things to help you debug.
First check if from your loginpage that upon successful login you are redirected to home.php?id=$id. Then check the URL if you have correct id
Use $_GET['id'] instead. You can try to echo $_GET['id']; to see if there's any value.

How to pass id in url when user login with his detail

hey every one i have on query plse help me
i want if user login with his login detail his id should be pass and should be visible in link bar ?id=000 like this.
i am trying lot but not able to resolve it plse help me guys...
<?php
include('db.php');
session_start();
if (isset($_POST['submit'])){
//$id= $_POST["id"];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$query = "SELECT * FROM register WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
header("Location:Employee/dashboard.php"); //here if user successfully log in his user id should be also visible in url bar
}else{
$query = "SELECT * FROM art WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
header("Location:Recruiter/dashboard.php");
}else{
echo "<script>alert('Incorrect user id and password')</script>";
}
}
}
?>
Below is the modification to your code that needs to be done. You will need to fetch id from the table, if the credentials are valid and append that id to the URL:
$query = "SELECT id FROM register WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_fetch_array($result);
if(isset($rows['id']) && $rows['id'] > 0){
$_SESSION['email'] = $email;
header("Location:Employee/dashboard.php?id=" . $rows['id']);
You don't have to send user_id from POST or GET, Set user_id in session at login time. and fetch it from session where you need it..this is the best solution..
OR
You can send it in your form as a hidden input
<input type="hidden" name="id" value="{$id}">
You probably get the answer from previous answers but I am adding this answer as the best practices to use the session to this kind of activity.
begins the session, you need to say this at the top of a page or before you call session code session_start();
put a user id in the session to track who is logged in $_SESSION['user'] = $user_id; . Then for Check if someone is logged in or not.
if (isset($_SESSION['user'])) {
// if logged in
} else {
// if not logged in
}
Find the logged in user ID $_SESSION['user'].
to redirect use this function:
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location.href=\'' . $url . '\';</script>');
}else{
header('Location: ' . $url);
die();
}
}
save user id in $_SESSION['id'] = $_POST['user_id']; and change your code like this:
if($rows==1){
$_SESSION['email'] = $email;
redirect(SITE_URL.'Employee/dashboard.php?id='.$_SESSION['id']); //here if user successfully log in his user id should be also visible in url bar
}
after user logged in check url everywhere you want like blow and if id not exist redirect again:
if(!isset($_GET['id'])){
$url = CURRENT_URL;
$url .= '?id='.$_SESSION['id']; //or $url .= '&id='.$_SESSION['id']; if some variables set befor
redirect($url);
}
Why did you want to display id in URL ?After login, you can access it from the user session. If you still want then here is the code.
<pre>
$query = "SELECT id FROM art WHERE email='$email' and pwd='$pwd'";
$result = mysqli_query($connection, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$data = mysql_fetch_assoc($result);
$_SESSION['email'] = $email;
header("Location:Recruiter/dashboard.php?id=".$data['id']);
}else{
echo "<script>alert('Incorrect user id and password')</script>";
}
}
}
</pre>

SESSION not remembered php

I came across the problem that my session vars aren't remembered when you are linked to another page. This might sound a bit strange. To clear it up a bit, I will explain my problem with some code:
This code is a snippet from 'Login.php'. Here I set the SESSION vars for Email and wachtwoord(Password).
$query = "SELECT * FROM user WHERE Email='$email' AND Wachtwoord='$Wachtwoord'";
$result = mysqli_query($connection, $query) or
die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
session_start();
$_SESSION['email'] = $email;
$_SESSION['wachtwoord'] = $Wachtwoord;
$sql = "UPDATE user SET Ingelogd = 1 WHERE Email='$email'";
$ressql = mysqli_query($connection, $sql) or
die(mysqli_error($connection));
}else{
echo "Invalid Login Credentials.";
}
Inside this snippet, the email and wachtwoord session are correctly set(I believe, because I can echo these and get the right output)
But when the user gets redirected to chat.php which contains this php code(indirectly, this code is in 'LoginCheck.php'. Linked to as: Include('../Php/LoginCheck.php');):
Include('connect.php');
//IF ((! $_SESSION['email']= NULL)&&(! $_SESSION['wachtwoord']=NULL)){
$email = $_SESSION['email'];
echo $_SESSION['email'];
$Wachtwoord = $_SESSION['wachtwoord'];
echo $_SESSION['wachtwoord'];
echo 'something';
$sql = "SELECT * FROM user WHERE Email='$email' and Wachtwoord='$Wachtwoord' and Ingelogd=1";
$result = mysqli_query($connection,$sql) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if (!$count == 1){
//header('Location: Login.php');
}
//}
When php tries to do something with a SESSION var it gives this error:
Undefined variable: _SESSION in F:\xampp\htdocs\Chives-Functional\Php\LoginCheck.php on line 4
The line, in which $email is declared.
What I want to check is whether the user is still logged in or not.
How can I get this to work? What am I doing wrong? And why isn't it remembered?
Thanks in advance, any help is appreciated!
Kind Regards,
Ps. If more information is required, feel free to ask!
Have you made sure to start the session on top of every page?
session_start();

Displaying specific data from mySQL using sessions IDs

I'm trying to display the users first name after they login. They login using their email and password. Though, I would like to collect their first name and display it. Their name is in the same table that the email/password are in. Traditionally, I would use a session ID like this below.
<?php
session_start();
$_SESSION['first'] = $first;
?>
But this typically is for submitted data in a form and is used after the form has been authenticated. My question is, how would I gather data from the mySQl table rather than collecting it from the form and be able to have it has a session ID?... if that makes sense
In your script where they login...just fetch the row and store into session...
Im using PDO, because thats much safer than the deprecated mysql_* functions you use in your login example.....
//start the session
session_start();
//Get their credentials, as follows...
$name = $_POST['username'];
$pass = md5($_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->execute(array($name, $pass));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0 ) {
//Store users info in a session
$_SESSION["username"] = $row["username"];
$_SESSION["firstname"] = $row["firstname"];
$_SESSION["auth"] = "set";
//Redirect to the user area, where you can echo their name
header ("Location: /app");
//Once in the user area, you can just echo their name like so...
//echo "Hello ".$_SESSION['username'].", Welcome to my site";
} else {
//Redirect back to login if their info is incorrect
header('location: /login');
//whatever your login page name might be...
}
But heres the code, if you don't wanna bother changing your site to utilizing PDO...
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=mysql_real_escape_string($_POST['username']);
$password=md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT id, username, firstname FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if(count($row)>0)
{
$_SESSION['auth'] = 'set';
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
header ("Location: /app");
}
else
{
$error="Your Hngout credentials are incorrect";
}
}
Select the first name (and any other fields you desire) when checking the user name and password match.
if (!isset($_SESSION)) session_start();
$sql=sprintf("SELECT email, firstname FROM users WHERE email=%s AND password=%s",
$_POST["email"], $_POST["password"]);
//You'd better use parameterized query
$result = mysqli->query($sql);
$row = $result->fetch_assoc();
if(mysqli->num_rows > 0)
{
$_SESSION["email"] = $row["email"];
$_SESSION["firstname"] = $row["firstname"];
}
else
{
//operation for no matches
}

Categories