Session not set till page reload? - php

So after a LOT of trial and error, I set up something to test whether my session is set or not, which looks like this :
<?php
session_start();
if (isset($_SESSION['email'])) {
echo "Logged In!";
}
else {
echo "NOT LOGGED IN!";
}
?>
And what I realize is that after Login ( which redirects to the site's homepage) The session is not set until I reload the entire homepagepage.
Has anyone experienced anything like this and/or knows how to get around such a problem?
Thanks in advance!

This snippet of code works for me as a test. Make sure your order of operations matches this. If that does not work, make sure you are allowing cookies in your browser. Failing that, there could be something screwy about your PHP/Apache configuration.
<?php
session_start();
if (!isset($_GET['test']))
{
$_SESSION['email'] = "something ".time();
header('location:?test');
die;
}else{
echo 'Value: "' .$_SESSION['email']. '"';
echo '<br /><br />< Do again';
die;
}
?>

Your pages need to be set up like so in this order (particularly the session_start()):
login.php
<?php
session_start();
// 1) Some code here to check database if username and password check out
// 2) If username and password check out and validation is good
// 3) Redirect to your next page (index.php in this case)
?>
index.php (home page)
<?php
session_start();
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><?php
if(isset($_SESSION['email'])) { ?>
EMAIL IS SET!! Great job!
<?php } else { ?>
UM...No..<?php } ?></h1>
</body>
</html>

I was having a horrible time with this. I have an index page that loads every time and inside a content div loads specific php scripts via include. I control the navigation of the website in this way by passing GET variables to the index.html, so my index page loads every single time no matter what content you're viewing. The very first line of index.html was:
<?php
session_start();
Some of my php scripts running as includes on the index page would set session variables then redirect to the index page and the session variable would not be there,, or they would not be set to what they should be. It was driving me mad, I could ctrl-F5 and sometimes they would show up and sometimes not. The only thing I can figure was that it was somehow opening different sessions for different urls that were in the address bar (by different urls I mean ones with different GET parameters. Simply putting this at the beginning of my index.html solved all my problems. I assume this causes the same session to open each time:
<?php
session_name('SessName');
session_start();

Thanks for all the help guys, but I found the problem.
Apparently I have to be extremely specific with my url in the redirect file.
I had header('location: http://domain.com');
instead of
header('location: http://www.domain.com');
...facepalm

Related

Trying to redirect based on session variable existence but it's not working

I want to ensure that an HTML page only appears if the user has logged in. I'm trying to do it by setting a session variable from the login page then checking if that variable exists when the HTML page is loaded.
This is my code at the very top of the HTML page:-
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("location: http://localhost/project/fail.php");
}
?>
It doesn't redirect! Nothing happens at all except that the HTML page gets loaded.
Can anyone help please?
Thank you all for your helpful suggestions. The snippet I posted shows the very first lines: i.e. session_start(); is the very first line.
By moving the var check snippet from the session_start() segment and making a separate php check snippet immediately after the body tag, everything works as expected.
You can use header function : https://www.php.net/manual/en/function.header.php
Referring to it :
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("Location: http://localhost/project/fail.php");
}
?>
make sure that session_start() always come at the first line
if(!isset($_SESSION['checks'])){
header('location: fail.php');
}
I believe your problem is on the login page... Although, if I were to talk about this page, consider trying the following code instead of your snippet first. If it gives the desired outcome then you will know that the problem is with your header and not the session:
<?php
session_start();
if (!isset($_SESSION['checks'])) {
echo "not logged in";
}
?>
Do make sure you're referring to the correct session variable if this code doesn't work and feel free to share how you are starting this session on your login page.

Php login script won't wrap around php

I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>

php- trying to have a text that can have 2 hyperlinks

I have a text that says "My Account" when a session is valid. When the user has already logged in, it should redirect them to AccountPage.html. If the user has not already logged in, it should redirect them to AccountLogin.html instead. I thought I could just add if statements like below but every time it runs to goes straight to login.html
<a <?php
if (empty($_SESSION["UserName"])) {
header("location:AccountLogin.html");
}
else {
header("location:AccountPage");
}?>> My Account </a>
You should study more. What you want is this code:
<?php
session_start();
$url = empty($_SESSION['UserName']) ? 'AccountLogin.html' : 'AccountPage';
?>
My Account
I highly discourage this kind of code where you mix HTML with PHP, the better would be to use some nice template engine like Smarty, Twig, Mustache, etc... You should study them too.
Bonus: location is a function that change the headers sent and instruct the browser to redirect to the specified url, hence it should be used when you need an hard redirect (and should be followed by an exit )
This is the code you're looking for. Ofcouse I can't be sure you're setting up the session somewhere the way you should. But if you do, this will work.
<?php
session_start();
if(!isset($_SESSION['UserName']) || empty($_SESSION['UserName'])){
//Personally I believe header("location") should only be used for hard urls but ok
header("location: AccountLogin.html");
} else {
header("location: AccountPage.html");
}
?>
I think you are setting up the link wrong.
Try this:
<?php
if (empty($_SESSION["UserName"])) {
$url = "AccountLogin.html";
}
else {
$url = "AccountPage.html";
}
?>
My Account

What is the proper way to display content after a user is logged in?

When I have a user logged in, it redirects to this page:
<?php
session_start();
if (isset($_SESSION['LoggedIn'])){
include "content.php";
}
else {
echo "You must be logged in.";
}
?>
What I just realized is that there is nothing stopping people from just going to the content.php page if they are logged out. Yeah, it won't show much, but what is the proper way to handle this?
I think you have things set up backwards. Instead of including content.php from the page that checks whether you're logged in, have content.php include the file that contains the check. That file should do something like:
session_start();
if (!isset($_SESSION['LoggedIn']) {
die("You must be logged in.");
}
Another option is to keep your current structure, but put content.php outside the web root, so it can't be addressed directly with a URL.
The issue is you should not just have one file/function be the gateway to content being loaded. But you need to create a structure for how content is accessed. So this code:
<?php
session_start();
if (isset($_SESSION['LoggedIn'])){
include "content.php";
}
else {
echo "You must be logged in.";
}
?>
Should perhaps be tweaked & added to an authentication.php file that behaves like this:
<?php
session_start();
if (!isset($_SESSION['LoggedIn'])){
echo "You must be logged in.";
die();
}
?>
The logic is basically: Is this user logged in? Good, do whatever else needs to happen on the rest of the page. If not, echo a message blocking them & exit via die(). And then in content.php—and any other page you want restricted—you load authentication.php like so as the very first thing the page does:
<?php
require_once('authentication.php');
[...rest of `content.php` goes here...]
?>
And you always do that require_once on every page you want restricted.
In your else statement, use something like this instead:
header("location:index.php");
Basically, you are saying if the user isn't logged in, redirect them to the homepage (or whatever page you specify, like a login page).
The only way to restrict access to any page is to check that access is granted for that user on that page. That means either adding
session_start();
if (isset($_SESSION['LoggedIn'])){
}
else {
//header redirect;
}
to every page, or having a functions/config etc type of file that runs all the functions you need and include that header in there.
I'd recommend making something called init.php and including that in every page. Inside init.php you can have the code above, so you wont need to have session_start() and checking for login everytime. Keep in mind though if your functions such as data inside content.php is dependent on the user_id (meaning you have a custom page based on the user who logs on) then you have to include the init.php before you run any functions dependent on that.
For example you have a functions.php file
// get data from mysql db
function say_hi()
{
$user_id = $_SESSION['user_id']
$sql = "SELECT * FROM users WHERE `user_id` = '".$user_id."'";
$result = $db->query($sql);
while ($rows =$chaptersResult->fetch_assoc())
{
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$date_registered = $rows['date_registered'];
}
echo $first_name. " ".$last_name. "You registered on: ".$date_registered;
}
then on content.php you want to do something like you wont be able to use that unless your inti.php (which will contain your $_SESSIONs for user ids and other stuff) is called BEFORE your functions.php.
for example
content.php
<?php
require_once 'init.php';
require_once 'functions.php';
echo say_hi();
?>
The order does matter, and as you learn more you'll eventually have a config file for database connections, etc.

Display output of PHP on another page

I got this simple hit counter off the internet and it's exactly what I needed:
<?PHP session_start();
if(isset($_SESSION['views'])){
$_SESSION['views']=$_SESSION['views']+1;
}
else{
$_SESSION['views']=1;
}
echo "Total page views= ".$_SESSION['views'];
?>
So I threw it in my home.html which needless to say is my homepage. I however want the views to be printed on my info.html page, but I want it displaying the hits for home.html. Does anyone know if that's possible?
Firstly you need to change your pages to .php extensions not .html if you need PHP to be compiled by the server.
There are probably a few ways of achieving what you need, however i will first point out a few things about php sessions you should know.
Session variables are available from any page on your site, providing a the session_start(); function is called first.
Sessions are essentially temp storage. In a nutshell a cookie containing a unique id is saved to the users computer. The unique id is reference to the session information stored on the server (temporarily).
For full info check out php.net
Because sessions are temp storage and they are unique to a user, you will not be able to show any users visits to the home page made by other users except themselves. To achieve this you would need to create a solution which has global and perminent storage (i.e. DB or File).
Now I will show you the solution to what you have asked, i just wasnt sure of the context, so thought i would explain the constraints.
Ok, so you should include the code below on home.php.
<?php
session_start();
if(isset($_SESSION['views'])){
$_SESSION['views']++;
} else{
$_SESSION['views']=1;
}
?>
This is exactly the same as what you had except i removed the echo function.
Now over on the info.php page add the following.
<?php
session_start();
if(isset($_SESSION['views'])){
echo $_SESSION['views'];
}
?>
This will then display the amount of times the user has viewed home.php.
Put this in your home.html
<?PHP session_start();
if(isset($_SESSION['views'])){
$_SESSION['views']=$_SESSION['views']+1;
}
else{
$_SESSION['views']=1;
}
?>
and this on your info.html
<?PHP session_start();
if(isset($_SESSION['views'])){
echo "Total page views= ".$_SESSION['views'];
} else {
echo "no page views to show";
}
?>
But you realize that this only counts a single persons visits, sessions are per person (devise) not shared. And that person will only see his own count; until the session expires.
And you many need to home.html to home.php for this to work! or set html files to parse as php

Categories