My sessions aren't working correctly - php

I have the following code
<?php
if($_SESSION['loggedin']){
echo '<li id="login-btn">Logout</li>';
}
else{
echo '<li id="login-btn">Login</li>';
}
?>
This is inside of the HTML for my Navbar. I want it to where if they are logged in, it will show "Logout", if they aren't logged in, it'll show "Login", (self explanatory)
I have this in my login.php
$loggedin = "";
$_SESSION['loggedin'] = true;
For some reason, no matter what I do, my navbar keeps displaying "Login"? Help please, thank you!

Session are global variables in php...
Session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning
of each page (session_start()).
if you want to access it on different page... you have to add
<?php
session_start();
?>
at the begining .... even in your login.php page

Related

Hiding a div based on session in PHP

I have a div that contains a slider when the homepage of the website is opened. What im trying to achieve is that when the website is opened for the first time, the slider should appear. However, if the user goes another page other than the homepage and then returns to the homepage again, the slider should not appear.
Below is the code I am trying to implement:
<div class="homeslidermain" style="display:<?php echo empty($_SESSION['first_load']) ? 'block' : 'none'; ?>">
<?php putRevSlider("typewriter-effect", "homepage") ?>
</div>
The recommended way would be to set a cookie using setcookie() and getcookie() (http://php.net/manual/de/features.cookies.php).
If you want to use the session then you are setting "first_load" incorrectly. Make sure that on any page call:
session_start(); // before you do anything else
if(!isset($_SESSION['first_load'])) // set it to true on first load
... and to false in any other case.
The only reason why this might go wrong is if you are reinitializing your session wrong. Make sure you are still in the same session after switching pages.
There is no need to output the div as display:none. Just output the div only when user visits the homepage for the first time. Use the setcookie() function to remember that user already visited he homepage, but please note that you should call this function before any output.
<?php
if (empty($_COOKIE['homepage_visited'])) {
// Remember the first visit for one year
setcookie('homepage_visited', 1, strtotime('+1 year'));
// Show the slider
echo '<div class="homeslidermain">';
putRevSlider("typewriter-effect", "homepage");
echo '</div>';
}
There are several ways to achieve it, best is to check if user visiting page for first time
session_start();
if(!isset($_SESSION['first_load']))
{
$_SESSION['first_load'] = '1';
}
if(empty($_SESSION['first_load']))
{?>
<div>
Slider block // this block loads only is first load is empty
</div>
<?php
}?>
You Could try something like this
// start the session
session_start();
$bShowBanner = true;
if(isset($_SESSION['BannerShown'])){
$bShowBanner = false;
}else{
$_SESSION['BannerShown'] = true;
}
?>
<div class="homeslidermain" style="display:<?php echo ($bShowBanner ? 'block' : 'none'); ?>">
<?php putRevSlider("typewriter-effect", "homepage") ?>
</div>

Using $_SESSION to carry a php variable from one page to the next?

I created an app to receive and tally votes. I am trying to make the voter's selection carry over to a confirmation page so that I can display the name of the candidate for whom they voted on the confirmation page.
I am trying to use $_SESSION on the variable of the selected candidate from the voter's submission, and then call the variable on the confirmation page, however I continue to get undefined variable error.
voterSubmit.php:
<?php
$selectedCandidate = $_POST['candidateid'];
session_start();
$selection = $_SESSION[$selectedCandidate];
//Redirect to results page
header("Location: views/confirmation.php");
confirmation.php
<?php
session_start();
$_SESSION[$selectedCandidate] = $selection;
include "views/confirmation.php";
confirmation view:
<?php include "../partials/header.php"; ?>
<h1>Thanks For Your Vote!!</h1><br>
//This is where the error occurs (on my selection variable):
<h2>You voted for <?=$selection?>
View Results
<?php include "../partials/footer.php"; ?>
I want the name of the selected candidate to appear on the confirmation page by way of the $selection variable. However, all I receive on the front end is an "undefined variable" error. I also would like to note that instead of using the $selectedCandidate variable in my session, I have also tried grabbing the name directly by just using the name of the radio button selection as such:
$_SESSION['candidateid'] = $selection
I also would like to mention that i have tried the reverse:
on confirmation.php:
session_start();
$selection = $_SESSION[$selectedCandidate];
on voteSubmit.php:
session_start();
$_SESSION[$selectedCandidate] = $selection;
Your using the $_SESSION variable incorrectly.
Try:
voterSubmit.php:
<?php
$selectedCandidate = $_POST['candidateid'];
session_start();
$_SESSION['selectedCandidate'] = $selectedCandidate;
//Redirect to results page
header("Location: views/confirmation.php");
confirmation.php
<?php
session_start();
$selection = $_SESSION['selectedCandidate'];
include "views/confirmation.php";
voterSubmit.php looks ok... but I don't understand why you have include "views/confirmation.php"; in the confirmation.php file.
<?php
session_start();
$_SESSION[$selectedCandidate] = $selection;
include "views/confirmation.php";
Try coding your HTML/PHP this way:
<?php
/* confirmation.php */
session_start();
$_SESSION[$selectedCandidate] = $selection;
require_once("../partials/header.php");
//This is where the error occurs (on my selection variable):
echo <<<_STRT
<h1>Thanks For Your Vote!!</h1><br>
<h2>You voted for $selection</h2>
<p>View Results</p>
_STRT;
require_once("../partials/footer.php");
?>
I essentially eliminated a lot of start/stop code. The start of your PHP recalls the session and variable. Then I go into the HTML portion to provide the results to your site visitor. Give it a shot. Comment on it if it doesn't resolve your issue so we can rethink it.
I think session_start() needs to be the first line after the php tag.
$_SESSION is an array. So you need to assign it values like:
$_SESSION['keyname'] = $value;
voterSubmit.php:
<?php
session_start();
$_SESSION['selectedCandidate'] = $_POST['candidateid'];
//Redirect to results page
header("Location: views/confirmation.php");
confirmation.php
<?php
session_start();
$selection = $_SESSION['selectedCandidate'];
include "views/confirmation.php";
There are 2 issues in your code :
session_start() defined in the wrong place.
Wrong way of assigning value to your session variable.
Answer :
session_start() should be the first thing defined after your php
tag.
Correct way to declare session variables is : $_SESSION["selectedCandidate"] = $selectedCandidate; where, $selectedCandidate is the value to be assigned to your session variable, named selectedCandidate.
You have done 2 mistakes in your code:
1. Session should be defined in starting of page it means you have to define it like this:
<?php
session_start();
//php code goes here.
?>
2.wrong initialization of session variable .you should do it like this:
<?php
$_SESSION['selectedCandidate']=$selectedCandidate;
?>

How to display a message visible just once on a page

After a user has registered on my website, I want to display a welcome message on the next page..
I want this to be visible just once.
I tried to do this with session but the problem is - it appears every single time the user is logged in and visits that page...
$message2 = "Congrats!! Your store has been created successfully!";
$_SESSION['message2'] = $message2;
header("location: admin/welcome.php");
Am building with php....but I dont mind using jquery etc for this.
In welcome.php, after the line that prints the message, unset $_SESSION['message2'] or empty it.
Example
echo $_SESSION['message2'];
unset($_SESSION['message2']);
// OR
$_SESSION['message2'] = null;
maybe you can use GET to make it work like this:
header("location: admin/welcome.php?message=$message2");
on welcome.php page
if(isset($_GET['message']) && !empty($_GET['message'])){
echo $_GET['message'];
}
Do you use start_session();
After displaying first you could set a $_SESSION['displayed'] = true;
then checking if this variable is set, to avoid display a second time

How to use $GLOBALS to share variables across php files?

I have a file, index.php that produces a link to a page that I want my user to only be able to access if some $var == True.
I want to be able to do this through the $GLOBALS array, since my $_SESSION array is already being filled with instances of a specific class I want to manipulate further on.
My index.php page:
<?php
$var = True;
$GLOBALS["var"];
echo "<p><a href='next.php'>Click to go to next page</a></p>";
?>
My next.php page:
<?php
if($GLOBALS["var"] == False)
exit("You do not have access to this page!");
else
echo "<p>You have access!</p>";
?>
Currently, next.php is echoing the exit text. Am I accessing/assigning to the $GLOBALS array correctly? Or am I not using it properly?
Thanks!
EDIT:
So I've tried some of the suggestions here. This is my new index.php:
<?php
$GLOBALS["var"] = True;
echo "<p><a href='next.php'>Click to go to next page</a></p>";
?>
My next.php:
<?php
if($GLOBALS["var"] == False)
exit("You do not have access to this page!");
else
echo "<p>You have access!</p>";
?>
However, I'm still running into the same issue where the exit statement is being printed.
It's much better to use sessions for this, since they are more secure and exist for this purpose. The approach I would recommend, is starting a new separate session array.
session_start();
$_SESSION['newSession']['access'] = true;
Then to access it use the same key/value.

I can't echo session username, am I storing session username and id correctly?

I am setting up a login form.
Expected Result:
Echo session username on page after successful login.
Actual Result:
Login is successful. Session username does not echo. Appears as though session username either does not exist or it is not persisting to the next page.
Is there something wrong with the code below?
LOGIN.PHP
...
session_start();
if (mysql_num_rows($result) ==1)
{
session_regenerate_id();
$row = mysql_fetch_assoc($result);
$profileid = $row['userid'];
$profile = $row['username'];
//Set session
$_SESSION['profileid'] = $profileid;
//Put name in session
$_SESSION['profile'] = $profile;
//Close session writing
session_write_close();
//Redirect to user's page
header("location: index.php?msg=userpage");
exit();
}
...
INDEX.PHP
...
<?php
session_start();
if($_GET['msg']=="userpage")
{
echo $_SESSION['profile'];
}
...
Edited:
Put session_start in php tags.
Changed HTML to INDEX.PHP.
"If" brace closed.
Changed while to if in LOGIN.PHP.
Changed username to userpage
You don't need to be opening/closing sessions, it's not worth the extra lines of code. I also don't know why you're regenerating the session ID.
But, one thing is your HTML file is badly constructed, and it almost looks like the session_start() isn't inside any PHP tags, so it's not even being treated as code.
first of all your HTML is yet PHP as it involves PHP tags only.
Replace while with if coz you only want to set the $_SESSION variables once.
And for the last part what you are looking for is this
<?php
session_start(); //at the beginning of your script
if($_GET['msg']=="username")
{
echo $_SESSION['profile'];
}
?>
Make sure you eliminate all the whitespaces before the opening of your first <?php tag on your script as that gives potential header errors.
close the if loop in html file
EDITED:
I did this simple code in my page and as per session concept is concerened The code is working fine...make corrections accordingly
p1.php
<?php
session_start();
//Put name in session
$_SESSION['profile'] = "Pranav";
//Close session writing
//Redirect to user's page
header("location: p2.php?msg=userpage");
exit();
?>
p2.php
<?php
session_start();
if($_GET['msg']=="userpage")
{
echo $_SESSION['profile'];
}
?>
FOR NEW SESSION ID
USE THIS
$a = session_id();

Categories