How to I use all user info in sessions - php

How do I use things like $email and $image in sessions when I only use username and password to log ind. It seems like I only can use $username ()
I don't know how to collect the last user info to sessions?
server.php
<?php
session_start();
// variable declaration
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// connect to database
$db = mysqli_connect('Localhost', 'user', 'pass', 'db');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
$uploaddir = 'assets/images/users/';
$image = $uploaddir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $image);
index.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: pages-login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: pages-login.php");
}
?>
...
<?php if (isset($_SESSION['success'])) : ?>
<div class="success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<ol class="breadcrumb">
<li class="breadcrumb-item active">
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<p>Hej <strong><?php echo $_SESSION['username']; ?>! </strong>Velkommen til Kommandocentralen</p>
<?php endif ?>
<?php echo $_SESSION['email']; ?>!
</li>
</ol>
I can not get it to give $email the same way it gives me $username.
I cut out a lot of the code between the php-bits

Following the same guidlines of the tutorial, on the server.php page, when the user registers or login, after the line that says $_SESSION['username'] = $username;, you can add other session data after that as follows:
When registering the user:
// REGISTER USER
if (isset($_POST['reg_user'])) {
...
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
...
}
When the user logs in:
// LOGIN USER
if (isset($_POST['login_user'])) {
...
$row = $results->fetch_array();
$_SESSION['username'] = $username;
$_SESSION['email'] = $row['email'];
...
}
For the user login, $results[0]['email'], references the email column of your database table so whichever data you want to make available, will need to use the same as is in the tabla. For example you would reference the image column as $results[0]['image'].
All other session variables can be set following the above pattern.
Hope this helps.

yes it worked - it stored the image in the folder I requested. but now I'm not sure how to show it?
// REGISTER USER
...
$uploaddir = 'assets/images/users/';
$image = $uploaddir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $image);
...
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['userfile'] = $image;
...
// LOGIN USER
...
$row = $results->fetch_array();
...
$_SESSION['username'] = $username;
$_SESSION['email'] = $row['email'];
$_SESSION['userfile'] = $row['userfile'];
...
And then in the index.php
...
<img src="<?php echo $_SESSION['userfile']; ?>" />
...
But nothing shows - can you se what my error is?

Related

Undefined index error when using session variables

I am working on a project where i already built signup, login, profile update forms.
Am using sessions to get currently logged in user info to be able to update his profile using profile update form. Now problem is that when i am assigning those session variables to update form. I get the following error.
This is my authController.php where all the processing of php is coded.
session_start();
$username = "";
$gender = "";
$dob = "";
$country = "";
$state = "";
if (isset($_POST['update-btn'])) {
if (empty($_POST['username'])) {
$errors['username'] = 'Username required';
}
if (empty($_POST['gender'])) {
$errors['gender'] = 'Gender required';
}
if (empty($_POST['dd'])) {
$errors['dd'] = 'Day required';
}
if (empty($_POST['mm'])) {
$errors['mm'] = 'Month required';
}
if (empty($_POST['yyyy'])) {
$errors['yyyy'] = 'Year required';
}
if (empty($_POST['country'])) {
$errors['country'] = 'Country required';
}
if (empty($_POST['state'])) {
$errors['state'] = 'State required';
}
$username = $_POST['username'];
$gender = $_POST['gender'];
$dob = $_POST['yyyy']."/". $_POST['mm']."/".$_POST['dd'];
$country = $_POST['country'];
$state = $_POST['state'];
if (count($errors) === 0) {
$query = "UPDATE users SET username=?, gender=?, dob=?, country=?, state=? WHERE id = '".$_SESSION['id']."'";
$stmt = $conn->prepare($query);
$stmt->bind_param('sssss', $username, $gender, $dob, $country, $state);
$result = $stmt->execute();
$stmt->close();
$_SESSION['username'] = $username;
$_SESSION['gender'] = $gender;
$_SESSION['dob'] = $dob;
$_SESSION['country'] = $country;
$_SESSION['state'] = $state;
$_SESSION['message'] = 'Your profile is updated!';
$_SESSION['type'] = 'alert-success';
header('location: updateprofileform.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not update user";
}
}
This is profile page.php just a small part of code where the error is pointed
<?php
require_once 'controllers/authController.php';
// If the session variable is empty, this
// means the user is yet to login
// User will be sent to 'login.php' page
// to allow the user to login
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You have to log in first";
header('location: login.php');
}
?>
<p class="user-info">
<b><span style="color:tomato;">Username : </span><?php echo $_SESSION['username']; ?></b>
<br>
<b><span style="color:tomato;">Gender : </span><?php echo $_SESSION['gender']; ?></b>
<br>
<b><span style="color:tomato;">DOB : </span><?php echo $_SESSION['dob']; ?></b>
<br>
<b><span style="color:tomato;">Country : </span><?php echo $_SESSION['country']; ?></b>
<br>
<b><span style="color:tomato;">State : </span><?php echo $_SESSION['state']; ?></b>
</p>
It shows undefined index error for gender,dob,country,state where i want to display the values using session variables
More INFO :
I have already started session in authController.php and linked it to update form using require once
Previously when i was working on this there was no problem and now whenever i open the profile page in browser it shows following error. When i submit the form with details the error disappears. But if i use this code on actual server the error displays when user first go to profile page i don't want that to be happen.
I know that if value is not assigned to the variable it shows this error but i have assigned the value
i don't know where am i going wrong
Can anyone help me with this
Thank you

I unable to show user name on the page after login session

Good evening guys, I faced some problem in PHP coding. I unable to show the user name on the next page after login even I had already included $_SESSION['username'] and session_start() in my codes. Can anyone help me to point out the problem? The code is as below:
login.php:
include_once 'dbconnection.php';
$msg = '';
if (!isset($_SESSION)) {
session_start();
if(isset($_POST['button']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$MM_redirectLoginSuccess = "dashboard.php";
$MM_redirectLoginFailed = "adminLogin.php";
$MM_redirecttoReferrer = false;
$username = mysqli_real_escape_string($dbcon,$username);
$password = mysqli_real_escape_string($dbcon,$password);
$sql = "SELECT * FROM admin WHERE user_name = '".$username."' and password = '".$password."'";
$result = mysqli_query($dbcon,$sql);
if ($count = mysqli_fetch_array($result))
{
$_SESSION['username'] = $count['username'];
$_SESSION['password'] = $count['password'];
header("location: dashboard.php");
$successmsg = "Successfully Register!";
echo "<script type ='text/javascript'>alert('$successmsg')</script>";
}
else {
$errormsg = "Wrong Username or Password. Please retry.";
echo "<script type = 'text/javascript'>alert('$errormsg')</script>";
}
}
}
?>
index.php:
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
}
?>
<!-- User Account -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="hidden-xs">
<?php echo $_SESSION['username'];?>
</span>
</a>
some issues with your code:
usage of header function: 'location' force a redirect so you should call only exit() after that.
check if a session is setted: you should do something like that from php version 5.4:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
use isset for something more specific like:
if (isset($_SESSION['username']){
// do something
}

Session variables not working? (PHP)

I am having an issue with 2 files: login_config.php and profile.php.
login_config.php consists of a log in system, which sets $_SESSION['key'] true upon the completion of several forms of authentication.
profile.php is the page the user is redirected to after success.
I want data on profile.php to only be accessible with $_SESSION['key'] set (upon successful login).
My question: What is incorrect with my code? Furthermore, why am I presented with the error upon login submission that is only supposed to return if $_SESSION['key'] is false/not set, as opposed to the targeted profile.php page?
CODE: (login_config.php)
<?php
// POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
// PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
if(!$veri_password === true){$errors[] = '-Account does not exist ';}
// CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$user_pass' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
// ERRS ARRAY ESTABLISHED
$errors = array();
// FURTHER VERIFYING
if( empty($password) || empty($email) )
{
$errors[] = 'Please do not leave fields empty';
}
elseif( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
$_SESSION['key'] === true;
while($row = mysql_fetch_array($entered_user)){
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
CODE: (profile.php)
<?php
session_start();
if($_SESSION['key'] !== true){
die ("please <a href='login.php'>log in</a> to view this page");
}
?>
<html>
<head>
<title>Profile</title>
<link href='css/main.css' rel='stylesheet' />
</head>
<body>
<div id='container'>
<?php require 'include/header.php'; ?>
<?= 'NJM ID # ==>'.$_SESSION['id'].'<br />'.'Username ==>'.$_SESSION['user'].'<br/>'.'Password ==>'.$_SESSION['pass'].'<br/>'.'<br />' ?>
<a href='logout.php'>Log out!</a>
<br />
-OR-
<br />
<p>Try our beta mode<a href='forum.php'> forum</a></p>
<?php require 'include/footer.php'; ?>
</div>
</body>
</html>
Note: I am aware I am vulnerable to SQL attacks at the current state of code, I will be fixing this later, also I am stuck with the deprecated version of MySQL.
In profile.php you have to call session_start(); before using $_SESSION. session_start() doesn't just start a new session, but will also continue an existing session (it will 'start' the session handling functionality, if you will). Without calling it, you cannot use $_SESSION.
1st: I would use termary operators for checking the existence of the values I need, for avoiding the "undefined index 'login_username'" error. Like this:
$username = isset($_POST['login_username']) ? $_POST['login_username'] : '';
$password = isset($_POST['login_password']) ? $_POST['login_password']) : '';
$email = isset($_POST['login_email']) ? $_POST['login_email'] : '';
2nd: I would use PDO for connecting with the MySQL server, for security reasons, and not only.
session_start();
if (isset($submit)){
// select all data from db for the current user
$st = $db->prepare('SELECT * FROM users WHERE email=?');
$st->execute([$email]);
//$rows = count_rows_here
if($rows == 1){
$row = $stmt->fetch();
if(password_verify($password, $row['pass'])){
$_SESSION['key'] = true; // notice the '=', and not '==='
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $row['email'];
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $row['password'];
header('Location: profile.php');
} else {
echo 'Error!';
}
}
}
I have fixed this by assigning the $_SESSION['key'] a variable with a value.
$_SESSION['key'] = $check = 'check';
Then to test this in profile.php, I have entered the following code:
if(isset(!$_SESSION['key'])){die ('example')}
I would try first to remove the exit() call after you have headered to the next PHP page. It isn't necessary as you have no code below it and it might be affecting the session (I don't think so though)
If this doesn't work (probably wont) add to profile.php after you have started the session var_dump($_SESSION) and have a look/post its contents.

Session missing after redirect (live server only)

I have been created a login page for user to login. The code is working properly in localhost but not in live server. User can't login on live server and I found out that everytime redirect to index.php, the session will lost, so that user can't login due to lost of session. You have any idea on this?
<?php
session_start();
include "header.php";
if (!empty($_POST)){
include 'database_connect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM users where username='$username' and password='$password'";
$result = mysql_query($sql, $con);
$rows = mysql_num_rows($result);
if ($rows == 1){
$_SESSION['username'] = $username;
echo "<script>window.location = \"index.php\";</script>";
//header("Location: index.php?" . SID);
}else{
echo "<div class='col-md-12 col-xs-8 alert alert-danger' align='center'>Invalid username and password. Please try again</div>";
}
mysql_close($con);
}
?>
Index.php
<? session_start();?>
<script>alert ('<?php echo $_SESSION['username']; ?>');</script>
Check session in your index.php page.just start session and echo user session. if you get then try if condition.
<?php session_start();
echo $_SESSION["username"];
if($_SESSION["username"]){
echo "bla bla";
}?>
<?php
session_start();
include "header.php";
if (!empty($_POST)){
include 'database_connect.php';
$username1 = $_POST['username']; // change it
$password1 = $_POST['password']; // change it
$username = stripslashes($username1); // change it
$password = stripslashes($password1); // change it
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM users where username='$username' and password='$password'";
$result = mysql_query($sql, $con);
$rows = mysql_num_rows($result);
if ($rows == 1){
$_SESSION['username'] = $username;
echo "<script>window.location = \"index.php\";</script>";
//header("Location: index.php?" . SID);
}else{
echo "<div class='col-md-12 col-xs-8 alert alert-danger' align='center'>Invalid username and password. Please try again</div>";
}
mysql_close($con);
}
?>
You write same name username /password before strip the username/password as well as after , so change the name and try once
In the below code,
<?php session_start(); // your header.php file should not have a session start in that file
include "header.php";
if (!empty($_POST)){
include 'database_connect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM users where username='$username' and password='$password'";
$result = mysql_query($sql, $con);
$rows = mysql_num_rows($result);
if ($rows == 1){
$_SESSION['username'] = $username;
?><script>alert ('<?php echo $_SESSION['username']; ?>');</script><?
echo "<script>window.location = \"index.php\";</script>";
exit();
//header("Location: index.php?" . SID);
}else{
echo "<div class='col-md-12 col-xs-8 alert alert-danger' align='center'>Invalid username and password. Please try again</div>";
}
mysql_close($con);
}
?>
You need to use session_start() function at the first line of the page after the php script starts

Android: http login request being redirected in php?

So this is a follow up to this post. I am attempting to log in using the code in the post linked. It works, however I believe there is something going on in the login.php file that I'm unaware of. Here is most of the login.php file, I apologize in advance for the wall of code.
<?php
session_start();
error_reporting(E_ALL^ E_NOTICE);
//include the connection and variable defination page
include("include/server.php");
include("include/function.php");
//checking the form has been submit by user or not
if(isset($_POST['cmdSubmit']) and $_POST['cmdSubmit']="Login")
{
//$refLink = $_SERVER['HTTP_REFERER'];
$refLink = "index.php?err_msg=1";
$user = addslashes($_POST['username']);
$pass = addslashes($_POST['password']);
$remember = $_POST['remember'];
$strErrorMessage = "";
if($user==""){
$strErrorMessage = "User Name can not be blank";
}
if($pass==""){
$strErrorMessage = "Password can not be blank";
}
if($user=="" and $pass==""){
$strErrorMessage = "User Name and Password can not be blank";
}
if($strErrorMessage=="")
{
if(isset($_POST['remember'])){
//removing all the cookie at set the user name password in cookies
unset($_COOKIE[session_name()]);
setcookie("usernamex", $_POST['username'], time()+60*60*24*100);
setcookie("userpassx", $_POST['password'], time()+60*60*24*100);
setcookie("rememberx", $_POST['remember'], time()+60*60*24*100);
}else{
if(isset($_COOKIE['rememberx']) && isset($_COOKIE['usernamex']) && isset($_COOKIE['userpassx']))
{
unset($_COOKIE[session_name()]);
setcookie("usernamex", $_POST['username'], time());
setcookie("userpassx", $_POST['password'], time());
setcookie("rememberx", $_POST['remember'], time());
}
}
$sqlLogin = "select * from member_mast where username = '".$user."' and password = '".$pass."' and is_deleted_flg=0 and is_profile=0";
$queryLogin = mysql_query($sqlLogin) or die(mysql_error()." Please check the Query");
$totLogin = mysql_num_rows($queryLogin);
//here checking the user is authorized or not
if($totLogin>0)
{
$rsLogin = mysql_fetch_array($queryLogin);
$_SESSION['uid'] = trim($rsLogin['username']);
$_SESSION['memberid'] = trim($rsLogin['user_id']);
$_SESSION['userType'] = trim($rsLogin['member_role']);
if(isset($_POST["page"]) and trim($_POST["page"])!="")
{
$pageName = trim($_POST["page"]);
$pagepassId = trim($_POST["pageid"]);
$redirect_url = "http://www.fakesite.com/fspv2/welcome.php?page=".$pageName."&pageid=".$pagepassId;
}
else
{
//$redirect_url = "http://www.fakesite.com/fspv2/welcome.php";
//$redirect_url = "welcome.php";
$redirect_url = "welcome.php";
}
//header("Location: ".$redirect_url);
?>
<script>window.location.href="<?php echo $redirect_url; ?>";</script>
<!-- <meta http-equiv="refresh" content="0;url=<?php echo $redirect_url; ?>"> -->
<?php
}
else
{
$displayMessage = "Login failed. If you are authorized, try again";
session_destroy();
$state = "inv";
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['pass'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
?>
<script>window.location.href="<?php echo $refLink; ?>";</script>
<?php
}
}
else
{
$state = "inv";
$_SESSION['username'] = $_POST['userid'];
$_SESSION['password'] = $_POST['pass'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$displayMessage = $strErrorMessage;
?>
<script>window.location.href="<?php echo $refLink; ?>";</script>
<?php
}
}
//header("Location: ".$refLink);
?>
<!--<script>window.location.href="<?php echo $refLink; ?>";</script>--> <!-- <meta http-equiv="refresh" content="0;url=<?php echo $refLink; ?>"> -->
Now when I connect to this login.php it doesnt matter if the username/pw is valid or not. The only response I get is this
05-18 17:08:50.160: V/RESPONSE(30797): <!--<script>window.location.href="";</script>--> <!-- <meta http-equiv="refresh" content="0;url="> -->
Which looks as though it's javascript attempting to redirect me because it's a mobile device. The only redirect I can find in there is to redirect the client to the "welcome.php" which would be if they successfully logged in. There does not appear to be a mobile login.php redirect in here (i may be wrong) It should be noted I did not design the site or any of the files I'm trying to access via my Android software, but I do have access to all the files. My question is if this is not the file/url I should be accessing, then what is, OR how do I find it? If you need to see any other code please just ask. Thanks!
Check if the following line results a true condition:
if($totLogin>0)

Categories