How do I send POST data to another session in PHP? - php

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.

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

Login script and stmt problems

I am having trouble the code executes correctly but when I submit with nothing in fields I get that you did not fill out all required fields message but when I submit with text in then I get the same message I do not know why
Also I am having stmt problems, I am trying to do a clean login script with stmt
login.inc.php
<?php
$ud = '';
$error = '';
$email = '';
$password = '';
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
if (empty($email) || empty($password)) {
$error = 'You did not fill out all the required field\'s.';
} else {
$stmt = $conn->prepare("SELECT id, username, password, email FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
if (!$stmt->execute()) {
$error = 'No account has the email: ' . $email . '.';
} else {
$ud = $stmt->get_result();
$stmt->bind_result($db_id_login, $db_username_login, $db_password_login, $db_email_login);
$stmt->store_result();
$password = md5($password);
if ($password == $db_password_login) {
// start users session
} else {
$error = 'The password is incorrect.';
}
}
$stmt->close();
}
}
?>
I have look at your code, and the main issue was your if statement logic in general and your prepared statement order and the way you have written you code. Here is a complete working solution.
I have changed password to plain text just for testing, but you should use better hashing then md5.
No reason to make your $username and $password empty at the top of the code.
I suggest you to use required="required" in input fields and make your email validation in your input field.
The login form can be done in many ways, I have just solved in regards to your code, but I suggest you to look at: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL for inspiration.
I have put my notes inside the code for your orientation.
<?php
// db connection
$dbcon_servername = "localhost";
$dbcon_username = "root";
$dbcon_password = "";
$dbcon_database = "dummy";
$conn = new mysqli($dbcon_servername, $dbcon_username, $dbcon_password, $dbcon_database);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// login logic
$error = "";
if (isset($_POST['login']))
{
// you can put the input var directly inside mysql real escape
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
if (empty($email) || empty($password))
{
$error = "You did not fill out all the required field\'s.";
} else
{
//sql statement for its own, cleaner and easier for debugging
$sql = "SELECT `id`,`username`,`password` FROM `users` WHERE `email` = ?";
if ($stmt = $conn->prepare($sql))
{
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
//check if you get at least one results you have to ensure you
//do not have double email as account, one way to that
//making email as key in your database and make email check
//mechanism to check for double when registering users.
if ($stmt->num_rows == 1)
{
$stmt->bind_result($db_id, $db_username, $db_password);
$stmt->fetch();
if ($password == $db_password)
{
// successful login
echo "The email address: $email with username $db_username exist in the database" . "<br />";
echo "id=$db_id, username=$db_username, password=$db_password \n";
} else
{
$error = "The password is incorrect";
}
} else
{
$error = "No account has the email: $email";
}
}
$stmt->close();
}
}
$conn->close();
?>
<html>
<head><title>Login form</title>
<head>
<body>
<h3>Login form</h3>
Click here to main page or some thing else</br>
<form action="form.php" method="post">
Enter Email: <input type="text" name="email"/></br>
Enter Password: <input type="password" name="password"/></br>
<input type="submit" name="login" value="Register"/>
<?php echo $error ?>
</form>
</body>
</html>

PHP login file is not working. Continues to return to the login page and not user profile

Here is the full code:
<?php
session_start();
session_regenerate_id(true);
require_once('connect.php');
require_once "lib.php";
require_once "utils.php";
$EmailAddress = mysqli_real_escape_string($link,htmlentities($_POST['EmailAddress']));
$Password = mysqli_real_escape_string($link,htmlentities($_POST['Password']));
$Fname = mysqli_real_escape_string($link,htmlentities($_POST['Fname']));
function login($result,$EmailAddress,$Password)
{
if($result)
{
if(mysqli_num_rows($result) == 1)
{
$email_exists = true;
$pass_exists = true;
if($pass_exists = true && $email_exists = true)
{
$_SESSION['active']=true;
$_SESSION['EmailAddress']=$EmailAddress;
//$_SESSION['Password']=$Password;
header("Location: myIndex.php");
exit();
}
}
else
echo "<div id='error'><h4>Error: Incorrect Password or Email</h4></div>";
}
}
function redirect_if_active()
{
header("Location: myIndex.php");
exit();
}
if(isset($_SESSION['active']) && $_SESSION['active'] ===true)
{
redirect_if_active();
}
// only processes login information if the submit button has been clicked
if (isset($_POST['submit'])) {
$sql="SELECT * FROM users WHERE EmailAddress ='$_POST[EmailAddress]' AND
Password ='$_POST[Password]'";
$result = mysqli_query($link,$sql);
login($result,$EmailAddress,$Password);
}
if(isset($_POST['signup'])){
header("Location: register.php");
exit();
}
?>
My guess is that the error is where the $sql = SELECT * FROM users WHERE but I', not entirely sure. I'll input the Email and the password, but it continues to return me to the login page. I'm not sure why it's doing that, but it needs to go to the Profile page once the user has logged in.
$link = "somethingrelatedtoyourdb";
$EmailAddress = $_POST['EmailAddress'];
$Password = $_POST['Password'];
//$Fname = $_POST['Fname']; THIS IS NEVER POSTED
echo "<pre>";
print_r($_POST);
echo "</pre>";
function login($result,$EmailAddress,$Password)
{
if($result)
{
if(($result) == true)//TRUE AGAIN
{
//THIS MAKES NO SENSE
// $email_exists = true;
// $pass_exists = true;
//if($pass_exists = true && $email_exists = true)
// {
$_SESSION['active'] == true;
$_SESSION['EmailAddress'] == $EmailAddress;
//$_SESSION['Password']=$Password;
header("Location: myIndex.php");
exit();
// }
}
else
echo "<div id='error'><h4>Error: Incorrect Password or Email</h4></div>";
}
}
function redirect_if_active()
{
header("Location: myIndex.php");
exit();
}
if(isset($_SESSION['active']) && $_SESSION['active'] ===true)
{
redirect_if_active();
}
// only processes login information if the submit button has been clicked
if (isset($_POST['submit'])) {
$sql="SELECT * FROM users WHERE EmailAddress ='$EmailAddress' AND
Password ='$Password'";
print_r($sql);
// $result = mysqli_query($link,$sql); Ill make this true for a moment
$result = true;
login($result,$EmailAddress,$Password);
}
if(isset($_POST['signup'])){
header("Location: register.php");
exit();
}
?>
<html>
<head></head>
<body>
<div id='form'>
<form action='example.php' method='POST'>
<div id='email'>Email:</div>
<div id='email2'>
<input name='EmailAddress' type='email'/>
<br>
</div> Password: <input name='Password' type='password'/>
<br>
<input class="submit" name='submit' type='submit' value='Login'/>
<input class="submit2" name='signup' type='submit' value='SignUp!'/> </form>
</body></html>
You have quite a few issues that I see right off the bat
In your sql query this $_POST[Password] should be $_POST['Password']. Same thing with the email address. This might fix your query, however please note, passing in raw post data to mysql is a big security problem. You are already setting these post params as escaped variables. You could use those, but you should look at prepared statements to keep yourself safe.
This block, has an error, and also doesn't make sense
$email_exists = true;
$pass_exists = true;
if($pass_exists = true && $email_exists = true)
It should be
if($pass_exists == true && $email_exists == true)
Or better yet
if($pass_exists && $email_exists)
However since you are explicitly setting both of these vars to true right before checking if they are true, then this will always be true.

I need help converting from mysql_query to PDO

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
}

HTML FORM + PHP: form action to remain on same page as login

at the moment my form links to a new page with all of my php code on it. I would like for all of the code to be executed on the same page as it does in this tutorial: http://www.w3schools.com/php/php_form_url_email.asp
I'm having some difficulty understanding exactly how this tutorial manages it. I was thinking maybe it would be possible to store my add.php code in a function and then call it with form action. Is this possible? If not what would be the best way to go about this?
here is my form code:
<form action="add.php" method="post">
<p>
Username: <input type="text" name="Username"><br>
Email: <input type="text" name="Email"><br>
Password: <input type="password" name="Password"><br>
Confirm Password: <input type="password" name="ConfirmPass">
</p>
<p>
<input type="submit">
</p>
</form>
and here is my add.php page:
<?php
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
$ConfirmPass = $_POST['ConfirmPass'];
$safeUsername = SQLite3::escapeString($Username);
$safePassword = SQLite3::escapeString($Password);
$safeEmail = SQLite3::escapeString($Email);
$safeConfirmPass = SQLite3::escapeString($ConfirmPass);
$hostName = explode('#', $Email);
$database = new PDO('sqlite:maindb.db');
$sql = "SELECT * FROM users WHERE Username = ?";
$result = $database->prepare($sql);
$result->bindParam(1, $safeUsername);
$result->execute();
if($result->fetch()) {
echo "Username " . $safeUsername . " already exists";
}
else {
if (filter_var($safeEmail, FILTER_VALIDATE_EMAIL) && checkdnsrr($hostName[1]) && !empty($safeEmail)) {
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$safeEmail)) {
if (!empty($safeUsername) && (preg_match("/^[a-zA-Z ]*$/",$safeUsername)) && !empty($safeUsername)) {
if ($safePassword == $safeConfirmPass && !empty($safePassword)) {
echo $Username . " was successfully added to the database.";
$stm = "INSERT INTO users(Username, Password, Email) VALUES(?,?,?)";
$stmt = $database->prepare($stm);
$stmt->bindParam(1, $safeUsername);
$stmt->bindParam(2, $safePassword);
$stmt->bindParam(3, $safeEmail);
$stmt->execute();
$database = null;
}
else {echo "Passwords do not match"; }
}
else {echo "Invalid Username.";}
}
else {echo "Invalid e-mail address.";}
}
else {echo "Invalid e-mail address.";}
}
?>
Thanks for the help! I appreciate it.
In the tutorial you linked they use
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//your stuff here
//save your form values etc.
}
to check if there has been a post to your page (this can be any page so also the same page). Basically this will check if a POST request has been send to this page. Which will if you use a from with a post method.
As an extra test they also put stuff like
if (empty($_POST["name"])) {
//name is empty print error!
}
in it to check if a field is empty or not.
all you gotta do now is change your action to the same page.

Categories