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
Related
I have a session that accepts login information and if user is valid within my database, I am setting the pages post array with the other data for user and displaying it in another session on a different page. My email and password are getting sent to the next session but the rest of my data isn't and I cant figure out why. I do know that I am successfully retrieving the data of the login user from the database table, however there is some issue with the other fields being sent to post and then on to the next session.
My login page
<?php
session_start();
if(isset($_POST["firstName"]))
{
$_SESSION["firstName"] = $_POST["firstName"];
}
if(isset($_POST["lastName"]))
{
$_SESSION["lastName"] = $_POST["lastName"];
}
if(isset($_POST["phone"]))
{
$_SESSION["phone"] = $_POST["phone"];
}
if(isset($_POST["email"]))
{
$_SESSION["email"] = $_POST["email"];
}
if(isset($_POST["sin"]))
{
$_SESSION["sin"] = $_POST["sin"];
}
if(isset($_POST["password"]))
{
$_SESSION["password"] = $_POST["password"];
header('Location: ViewAllEmployees.php');
exit;
}
require "MySQLConnectionInfo.php";
$error = "";
// if email and password not set
if (! isset($_POST["email"]) || ! isset($_POST["password"])) {
$error = "Please enter employee login information.";
} else {
// if email and password set from login input
if ($_POST["email"] != "" && $_POST["password"] != "") {
try {
$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully" . "</br>";
$sqlQuery = "SELECT * FROM employee";
try {
$result = $pdo->query($sqlQuery);
$rowCount = $result->rowCount();
if ($rowCount == 0)
echo "There are no rows to display from the Employee table ";
// find employee
for ($i = 0; $i < $rowCount; $i++) {
$row = $result->fetch();
$firstname = $row[1];
$lastname = $row[2];
$email = $row[3];
$phone = $row[4];
$sin = $row[5];
$password = $row[6];
if (isset($_POST["email"]) && isset($_POST["password"])) {
if ($email == $_POST["email"] && $password == $_POST["password"]) {
$_POST["firstName"] = $firstname;
$_POST["lastName"] = $lastname;
$_POST["email"] = $email;
$_POST["phone"] = $phone;
$_POST["sin"] = $sin;
$_POST["password"] = $password;
break;
}
}
}
} catch (PDOException $e) {
echo "Login unsuccessful. " . $e->getMessage();
}
$pdo = null;
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
} else
$error = "Please enter employee login information.";
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
include "Header.php";
include "Menu.php";
?>
<div class="content">
<form action="Login.php" method="post">
Email Address: <input type="text" name="email" /> <br /> Password: <input
type="text" name="password" /> <br /> <br /> <input type="submit"
value="Login" />
</form>
<br /> <br />
</div>
<?php
echo $error;
include "Footer.php";
?>
</body>
</html>
The problem here is, you set the $_SESSION array before you assigning them to the $_POST array. The moment you assign the $_SESSION['firstName'] = $_POST['firstName'], the $_POST['firstName'] is empty.
Solution : Move the area where you set the $_SESSION variable
if(isset($_POST["firstName"]))
{
$_SESSION["firstName"] = $_POST["firstName"];
}
after you setting the $_POST variable.
if ($email == $_POST["email"] && $password == $_POST["password"]) {
$_POST["firstName"] = $firstname;
$_POST["lastName"] = $lastname;
For the email and the password, these fields get saved in the session because you're passing these two POST fields from the HTML Form and in the top section where you set the $_SESSION variable, these two fields are already populated in the $_POST array.
There are some parts of the code that could be improved, like:
Add the email directly here in a WHERE clause, so that you don't need to do a for loop for all the employees.
$sqlQuery = "SELECT * FROM employee";
if (isset($_POST["email"]) && isset($_POST["password"])) in the try block is not necessary and could be moved up and replace the first check (where you are using != "").
Regardless, to answer your question you need to know a bit of how the flow of the code is. The reason the other information isn't being sent to other page is that where you are setting the $_SESSION variable, that information isn't available to the code.
You have a form in your html that sends data to your code. This will only populate $POST["email"] and $POST["password"]. In the beginning of the code you are checking for other data in $POST which aren't yet populated therefore they won't be saved in $_SESSION.
If you insist to not using Kinglish's approach from the comments, you should move $_SESSION["phone"] = $_POST["phone"], etc to where you have found the user from the database.
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?
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.
I want to make my site as secure as possible so i need to convert everything i have to PDO. I've successfully done a few things but i ran into a road block on my Sign In page.
Heres my code:
<?php
//signin.php
include 'connect.php';
include 'header.php';
session_start();
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can signout if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<div class="formdivs" id = "logindiv"><form class = "homeforms" method="post" action="">
<label>Username:<input class="forminput" id="smallinput" type="text" name="user_name" /></label>
<label>Password:<input class="forminput" id="smallinput" type="password" name="user_pass"></label>
<input class = "formbutton" type="submit" name = "button" value = "Sign In!"/>
</form></div>';
}
else
{
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
else
{
//THIS IS WHERE MY PDO PROBLEM BEGINS-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
$password = sha1($_POST['user_pass']);
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :password";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':password', $password);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if(true)
{
if(true)
{
$_SESSION['signed_in'] = true;
while($row = $stmt->fetch())
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
header('Location: /forum.php');
exit;
}
}
}
}
}
include 'footer.php';
?>
My page loads the form but when i press my submit button it turns blank (except for my header and footer) which tells me my php has an error. (obviously)
I want my page to be able to run its error checking (to see if both boxes have input) then to execute upon button press. After i press the button i want it to echo an SQL error if there is one (in situations where the database is down etc) And then also echo if the user name or password does not exist in the database. (IE the select statement returns nothing).
At the moment i have "admin" and "password" just hardcoded in, because i dont think my bindparams statements worked.
EDIT: i should also state that none of my error checking works. If i try to run it with the boxes empty nothing is still shown.
EDIT: SOLUTION: I was using $pdo when i should have been using $DBH. I didnt realize the $pdo variable from the php manual was supposed to be the actual instance i created in my connect.php file. Thanks for your help everybody
You need the colon in your SQL string
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :userpass";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':userpass', $password);
$stmt->execute();
no need for loop , since it's a single record:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
//set your session
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
Keep things simple
if(isset($_POST['submit']){
//form submitted, checking errors
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
exit();//error! let's exit
}else{
//No errors run the PDO query here
}
}else{
//no submission display the form
}
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)