Session variable appears empty on different page - php

Edit: after doing some trial and error stuff I notice that if I comment the following code:
$success = $_SESSION["success"];
session_unset($_SESSION["success"]);
the $to variable displays as intended. So my question is why can't both be at the same time used?
Original question:
I'm trying to send an email using the mail() function. In order to do that I pass the variable $_SESSION['emailfrompass'] across 2 pages but for some reason the variable is always empty. Even though there is another variable that I send with a message and I have no problems in receiving it, this is the only one that makes problems
The session_start() is set across all pages. I tried using
ini_set('display_errors',1);
error_reporting(E_ALL);
for finding the problem but no use. The variable is always empty
This is my enterEFPass.php file. On top I have
<?php
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
?>
<?php
if(isset($_SESSION["success"]))
{
$success = $_SESSION["success"];
session_unset($_SESSION["success"]); //echoing this will display the right thing
$to = "";
$to = isset($_SESSION['emailforpass']) ? $_SESSION['emailforpass'] : 'not found';
echo $to; //does not work
//mail($to, "Reset your password", $message, $headers);
?>
<div id='alert'>
<div class='alert alert-block alert-info'>
<?php
echo $success;
// echo "<script>setTimeout(\"location.href = 'login-page.php';\",2500);</script>";
?>
</div>
</div>
<?php
}?>
And this is the enterEFPass_route.php in which I instantiate the $_SESSION variables
<?php
session_start();
include 'db.php';
$email = "";
$conn = Connect();
if (isset($_POST['send_email_button']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']); //$_POST['email'] the field where I introduce the email
}
if (empty($email)) { array_push($errors, "Please enter a valid email"); }
if (count($errors)==0) // just an array for error messages
{
$_SESSION['emailforpass'] = $email; //appears empty always
$_SESSION['success'] = "An email has been sent to the corresponding address. Please follow the instructions provided there"; //goes without problems
header("location: enterEFPass.php");
} else
{
$_SESSION['errormsgpassress']= $errors; //no problems in sending
header("location: enterEFPass.php");
}
}
?>
I expect the $to variable to print on the screen but it always prints "not found"
If I print $_SESSION['success'] there is no problems in that

The method session_unset() does not take any arguments. It is used to unset ALL session variables, thus it is unsetting the $_SESSION['success'] variable. See here for more details on that. Instead, use unset($_SESSION['success']); to unset a single session variable. Hope this helps!

Related

PHP Session Variable: Error Undefined Variable

So basically its creating a session using the users email and password. Checking whether it has an email and password entered and if not redirecting them back to the login page. Hence:
<!DOCTYPE html>
<?php
session_start();
include 'connect.php';
if(!isset($_SESSION['email']) || !isset($_SESSION['password']))
{
header("location:loginTemplate.php");
}
else
{
$_SESSION['email'] = $email;
}
?>
So I then want to use the $email variable to essentially welcome the users. Hence:
<h2>Welcome <?php echo $email; ?></h2>
But I am getting an error saying the variable is undefined
if(!isset($_SESSION['email']) && !isset($_SESSION['password']))
{
header("location:loginTemplate.php");
}
else
{
$email = $_SESSION['email'];
}
You have not defined $email anywhere.
Correct the line:
$_SESSION['email'] = $email;
To
$email = $_SESSION['email'];
You need to get email value from Session, and you are trying to assign value to session variable.
Thats it.
Try to change your logic to:
if(!isset($_SESSION['email']) && !isset($_SESSION['password']))
Probably, your session was not set because you wasn't redirected to loginTemplate.php, so with OR option, it will fail to enter the desired condition but will work with && condition.

Login / Logout Session Issue

I am creating some kind of a login/registration system right now. Registration form, email confirmation and login is already working. I now have problems with my sessions. Please keep in mind that this project is just a test project. I know that I should use PDO but for this testing purposes I need to find out why it is not working they way I did it.
Here is my login.php PHP code:
<?php include ('inc/database.php');
if (isset($_POST['submit'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwort'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwort'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM user WHERE email='$Email' AND password='$Password' AND activation IS NULL";
$result_check_credentials = mysqli_query($connect, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (#mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
//Assign the result of this query to SESSION Global Variable
header("Location: index.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
} // End of the main Submit conditional.
?>
Here is the beginning of my protected index.php
<?php
ob_start();
session_start();
if(!isset($_SESSION['email'])){
header("Location: login.php");
}
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
.....
There must be a problem with my session and I do not know why. Is it wrong to use the email as session? Am I using the email as session? What other options do I have?
Problem is right now, that if I click on Login, nothing happens. I will be redirected to login.php instead of index.php!
Any suggestions?
As Fred -ii- already mentioned in comments above, your $_SESSION['email'] is never set, and therefor you are re-directed to your login-page every time.
It's also worth noting that when using header("Location: ...");, you can not have any output prior to the header! Otherwise the header will fail. Output is generally any HTML, echo, whitespace (see this SO).
So, once you make sure that your header("Location: index.php"); actually works, move on to fixing your $_SESSION.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC); does not set $_SESSION['email'] (as already stated by Fred -ii-). To fix this, you need to fix your results from the database.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
The code above will return the row "email" from the result in the database, and set it to the session of "email", which later is checked when you are trying to access index.php.
A couple of side-pointers (not really your current problem, but a few tips to make your code better).
You should use exit; after using header("Location: ..."); (See this SO)
You are not hashing your password, so it's stored in plain-text in your database (big no-no)
Indenting your code properly makes it a lot easier to read, and in turn easier to troubleshoot
If you do the above, and it still doesn't work, we'd need some more information to help troubleshoot further (like what happens when you're logging in (is it as expected?), what results are returned, and so forth).
try to change,
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
to
$results = mysqli_fetch_row($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email']=$results['email'];
and try to check your "activation" field in database for null while login...

PHP Session variables not persisting

I'm creating a site that uses sessions to store login details - I know its a bad security practice but that'll be dealt with later; for now I just need to fix this issue. Page 1 gets the login details from a login form and stores them in a session. Page 2 is meant to display those variables, but I get these errors when trying to access the variables:
Notice: Undefined index: email in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 10
Notice: Undefined index: password in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 11
Here is the code - I've left off the unrelated parts:
Page 1
session_start();
var_dump($_SESSION);
ini_set('display_errors',1);
error_reporting(E_ALL);
// Just logged in
if($_POST["email"] != "" || $_POST["password"] != ""){
$email = strtolower($_POST["email"]);
$password = md5($_POST["password"]);
$_SESSION["email"] = $email;
$_SESSION["password"] = $password;
//echo "setting details from http post";
}else{
// Just redirected to this page
$email = $_SESSION["email"];
$password = $_SESSION["password"];
}
And page 2 where I'm getting the errors mentioned above:
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
var_dump($_SESSION);
$_SESSION["advert"] = $_GET['id'];
echo $_SESSION["email"];
echo $_SESSION["password"];
I've searched SO and have made sure there are no spaces or whatever before my session_start();
By the way, if it helps my domain company that I'm using is One.com
$_SESSION["email"] and $_SESSION["password"] are set in the if, so in the case it is skipped you get this undefined indexes error (as elements with this indexes were not defined anywhere before).To get rid of this Notice you can use isset() function(also use it to validate $_POST user input). Example :
echo isset($_SESSION["email"]) ? $_SESSION["email"] : 'There is no element with key "email"';
P.S. Validating your POST input :
if(isset($_POST["email"]) && isset($_POST["password"])){}
Change condition to:
if(isset($_POST['email']) && isset($_POST['password'])){
//do login
}
else {
echo " Plese enter email and password";
}
For full:
Login.php
<?php
//here must be totaly clear, nothing can't be here
session_start();
if(isset($_POST['email']) && isset($_POST['password'])){
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $_POST['password'];
}
else {
echo "Please enter email and password";
}
//here must be form to login
Logged.php:
<?php
//here must be totaly clear, nothing can't be here
session_start();
if(!isset($_SESSION['email']) && !isset($_SESSION['password'])){
header("Location: Login.php?err=Please login to use members area");
}
else {
echo "You are logged in as:". $_SESSION['email'];
}
I solved the problem. When I was on one page I was on www.domain.com/page1 but when I was on the other page there was no www - domain.com/page2. This meant that session variables were not persisting. To fox this, I need to edit the htaccess file to redirect to www if there is no www in the URL.

PHP array stored in session not working if I redirect to another page

I am trying to check a form input data for errors -> store it in an array -> save it as a session and go back to the form page and show the errors.
But somehow the array stored in session doesn't work after I redirect back to Form page.
I just shows an empty array.
Here is the form page code:
<?php
session_start();
$error = $_SESSION['error'];
print_r($error);
unset($_SESSION['error']);
?>
//html form
And here is error check page code:
<?php
session_start();
$error = array();
if(isset($_POST['email'])){
$email = $_POST['email'];
}
else{
array_push($error, 'Enter Email Address');
}
$_SESSION['error'] = $error;
header('location: form.php');
?>
Kindly help. Or any alternative?

Why POST['submit'] is set when I reload?

My application is a simple login page. When it fails, I print an error message. My question is, why when I reload the page the message is been printed again? How can I fix that?
The code is working fine, I've made another php file executing the database check & connection.
<?php
require_once("include/database.php");
if(isset($_POST['submit'])) {
connect_bookstore(); // custom function
$spassword = sha1($_POST['password']);
$username = $_POST['username'];
if ( checkpassword($username,$spassword) ) { //custom function
header('Location:insert.php');
exit;
} else {
$message = "Login failed!";
}
}
?>
Inside the html body.
<?php
if (isset($message)) {
echo $message;
}
?>
<?php
session_start();
require_once("include/database.php");
if(isset($_POST['submit'])) {
connect_bookstore(); // custom function
$spassword = sha1($_POST['password']);
$username = $_POST['username'];
if ( checkpassword($username,$spassword) ) { //custom function
header('Location:insert.php');
exit;
} else {
$_SESSION['message'] = "Login failed!";
header('location: /yourfile.php');
exit;
}
}
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
Fundamentally, yes, post/redirect/get... but sometimes a simple explanation is better.
I use sessions to store flash messages, then display them like this.
Thats because you are resending the same POST data when you refresh, if you do a GET request you will notice in the URL your parameters that you are passing are there, so if you refresh those parameters are once again sent. Same thing with POST.
When you reload the page, the browser will send the same request that it sent for theoriginal page.
You want a POST-Redirect-GET.

Categories