PHP Session Variable: Error Undefined Variable - php

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.

Related

Session variable appears empty on different page

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!

Displaying error of undefined index on login?

So I am working on a Login Portal and I want the user to not go directly to the link -
http://localhost/working/HomePage.php
So I added this piece of code in HomePage.php -
session_start();
if($_SESSION["user"] == null)
{
include 'Login.php';
}
I am setting up the session variable in another file AccessControl.php
if ($_POST['password'] == "password" and $row["Emp_Password"] == "password")
{
include 'ChangePassword.php';
}
elseif ($row["Emp_Password"] == $_POST['password'])
{
$_SESSION["user_pwd"] = $_POST['password'];
$_SESSION["user"] = $_SESSION["user_id"];
header('Location: HomePage.php');
}
else
{
echo "<script type='text/javascript'>alert('Invalid Password!');</script>";
include 'Login.php';
}
When I try to access the HomePage.php it is redirecting me to Login page but with a error -
Notice: Undefined index: user in C:\xampp\htdocs\Working\HomePage.php
on line 8
Is their any way that I might get redirected to the homepage and also this error isn't displayed?
Also after I am redirected to Login.php I can't Login.
Thanks in advance.
You can do something like I have done below and instead of include I would recommend header. Also use empty as stated in the above answer.
session_start();
if (empty($_SESSION["user"]))
{
header("Location:Login.php");
}
You can make check as follows:
session_start();
if(empty($_SESSION["user"])) {
include 'Login.php';
}
Read more about empty.

Using variables with PHP session

I'm trying to get a user on my web shop to enter a username which will then be displayed on each page. I've started the session here in header.php and set the username variable:
session_start();
$_SESSION['username'] = $username;
$username = ''; //set blank variable to be filled in index
I'm then calling header.php in index.php using:
<?php
include "header.php";
?>
Inside of the logIn div I'm then asking for the username to be entered (no form to submit it yet, haven't gotten that far without running into the problem below). The script should show a message if the user isn't logged in alongside a form to log in, but if they have submitted a username to use then the form should display a welcome message:
<div class="logIn">
<?php
if (!isset($_SESSION['username'])) {
echo 'Welcome, '.$_SESSION['username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
</div>
I'm currently getting this error:
Notice: Undefined variable: username in /header.php on line 13
but I can't figure out why. I thought I'd declared it as empty, but even when I give it a value the if statement in index.php isn't working as intended.
How can I set up a simple session and accept a username variable (no password) which will then be displayed on index.php?
Your error is simple .
$_SESSION['username'] = $username;
$username = '';
You are trying to use $username before assigning it.
$username = '';
$_SESSION['username'] = $username;
Should be better !
I guess line 13 is this one $_SESSION['username'] = $username; ?
If you are assigning $username to $_SESSION['username'] it must be set somewhere before, I can't see that in your example.
Your code has to look something like this:
//declare $username
$username = "somename";
$_SESSION['username'] = $username;
Or if you set $username in a condition or something else you can try this:
$_SESSION['username'] = ( isset( $username ) ) ? $username : '';

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.

isset($_SESSION) display $_SESSION name

If anyone can make a better title, please edit it.
The issue I am having is being unable to show the users name in their post. Quick snip of code.
if (isset($_SESSION['username']) )
{
$name = $_SESSION['username'];
}
else
{
$name = $_POST['name'];
}
How can I make it when the user posts it check to see if there is a session and then displays their name in their post.
There's nothing particularly wrong with what you've done here. Does $_SESSION['username'] actually have a value?
Also, make sure when you are working with sessions that you call session_start() before saving or pulling session data.
<?php
session_start();
$_SESSION['username'] = 'Greg';
if (isset($_SESSION['username']) )
{
$name = $_SESSION['username'];
}
Please try the following
session_start();
if (isset($_SESSION['username']) )
{
$name = $_SESSION['username'];
}
else
{
$name = $_POST['name'];
$_SESSION['username'] = $name;
}
Then reload the page, $_SESSION['username'] now should contain the user name
Garrett am i right in thinking your route is create $_SESSION['name'] first and regardless unless they have logged in if so the $_SESSION['name'] becomes $_SESSION['username']
If I am right and you are creating $_SESSION['username'] on login all you need to do is check if $_SESSION['name'] = $_SESSION['username'] and if it does unset it example:
// YOUR LOGIN CODE TO CHECK ASSUME SQL QUERY OF SOME DESCRIPTION AND 'true' IS YOUR RESULT and 'false' NOT A USER
if(true) {
$_SESSION['username'] = $result;
if($_SESSION['name'] && $_SESSION['name'] == $_SESSION['username'] ){
unset($_SESSION['name'])
}
// ACTION TO GO TO PAGE
} else {
// YOUR ERROR ACTION
}

Categories