PHP $_SESSION variables not renewing on page template - php

Page A and Page B both use PHP page template 1, which is storing get_the_title(); in $_SESSION['pagesource'] = get_the_title(); and sending it to another php file.
However, after visiting page A, then going to page B the variable stills shows the pagesource for Page A until I refresh the page. How do I clear the session so the $_SESSION['pagesource'] is available and true for both pages?
I'm using session_start(); on both pages
Thanks

Try this, at the top of Page B (or indeed any page)
<?php
//Remember to start the session on each page
session_start();
//Unsets all session variables without discretion - ony use if strictly necessary
session_unset();
//Destroys the session, again without discretion - ony use if strictly necessary
session_destroy();
//Typical way to unset any variable
unset($_SESSION['pagesource']);
//Create a new $_SESSION['pagesource'] session variable and set it equal to what get_the_page_title() returns
$_SESSION['pagesource'] = get_the_page_title();
//do anything you want with the page title
exit();
?>
I am very much covering all bases there; try this and if if works we can work on refining it

Related

How to allow a user to go back on PHP page?

I have implemented session into my application, but I need to allow the logged in user to use the back button to go to the previous pages.
How do I make sure that the session does not expire and allows the user to view the previous page?
Here is my code
<?php
//Start session
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$User = $_SESSION["User"];
//Page content
?>
I have started the session, when I use the back button on browser I get a page that reads session has expired. Which I do not want to happen.
in your php at the top of each page, start your session before your opening <html> tag
<?php session_start(); ?>
<html>
in your php somewhere set your session variables note this value must be serializable
<?php $_SESSION["variable"] = "value"; ?>
then anytime you want to access that session variable you can do the following AFTER calling session_start();
<?php echo $_SESSION["variable"]; ?>
if you handle your sessions in this manner, session variables will be available on previous and future pages.
caveat:
depending on browser and headers sent from your server, when you go back a page, it reloads the page as it was in the cache so consider the following:
User goes to page and is does not have a session variable set
User does action that sets a session variable and sends them to a second page
User hits back button
User is shown the pre-session cached version of the first page
User refreshes page
User now sees the first page w/ session variable set
the reason for the hiccup is that some browsers do not always make a new request on back button sometimes it loads from the browser cache. read the very end of this answer: https://stackoverflow.com/a/1313941/884453
EDIT
You posted code above with a check to session_status first. This is incorrect. You ALWAYS need so session_start();
<?php
//Start session
session_start();
// User is either pulled from the session or is null
$User = $_SESSION["User"] ? !empty($_SESSION["User"]) : NULL;
//Page content
?>
the code for if (session_status() !== PHP_SESSION_ACTIVE) { is only useful in situations where some other bit of code (usually in a framework) may have started the session already.
If you have set up your session management correctly, you don't need to do anything.
However, this correctly depends on what kind of state you have in the session and how you manage it. Also timeouts will still apply (as they should).
You can use javascript history method also for that so your session also remain same.
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

PHP session variables life

Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>

$_SESSION variable in php (page to page)

Whenever I go to a page i.e. login page or any other page, I want to save the name of the page in a $_SESSION variable.
login page:
<?php
session_start();
$_SESSION['page'] = 'login.htm';
?>
It works only for the login page and doesnt overwrite in other pages for e.g. home page:
<?php
session_start();
$_SESSION['page'] = "home.htm";
?>
I need the sesssion variable 'page' to hold the last page I was, can anyone help please?
Why not just use $_SERVER['HTTP_REFERER']? This will give you the previous page in PHP, without having to add anything to sessions.
when you navigate to a new page first retrive the saved "back" variable (and use it in a back link/breadcrumbs or something), and then overwrite the sessions "back" variable with the curent page, to have it ready for the next move =)
If all you need is default "back" functionality you should let the browser handle it.
If what you want is something to be used as a breadcrumb following some internal order (or path in a tree) my advice is to let each page "know" the path that leads to it.
If you really need to know from what page the user came from save it to a previous variable before you write over the current variable.
// Make sure user didnt just refresh the page
if ($_SESSION["current"] !== "currentPage.php") {
$_SESSION["previous"] = $_SESSION["current"];
$_SESSION["current"] = "currentPage.php";
}
You're using different keys.. 'page' and 'back'.

PHP: Checking Session State on Secondary Pages

I am working with a PHP Login System from http://tutorialzine.com/2009/10/cool-login-system-php-jquery/ Just to give you a quick overview, I believe the tutorial sets up the variable in the following manner:
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('tzLogin');
// Starting the session
session_set_cookie_params(1*7*24*60*60);
// Making the cookie live for 1 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
..........
So far so good, except that I cannot carry over the session variables from the Main Login page to subsequent pages (which contain restricted content). Here is the basic code that I intend to place at the start of each restricted content page
<?php
session_name('tzLogin');
session_set_cookie_params(1*7*24*60*60);
session_start();
if($_SESSION['id']) <-- I believe I need more code here (incldue the cookie)
{
//If all is well, I want the script to proceed and display the HTML content below.
}
else
{
header("Location: MainLogin.html");
or die;
//redirects user to the main login page.
}
?>
As you can see, I am a total novice, but any help would be greatly appreciated. As of now, my restricted content pages keep getting redirected to the homepage even when I am properly logged in. Hence I suspect, the SESSION state is not being carried over. Thanks again!
You should probably make sure that you set the path and domain when you invoke session_set_cookie_params:
session_set_cookie_params ( 1*7*24*60*60, '/','.yourdomain.com')
See http://php.net/manual/en/function.session-set-cookie-params.php
(It's a good idea to set the httpOnly attribute as well.)
Additionally, make sure you actually assign some value to your session id key (it's not clear in your code sample that you do):
$_SESSION['id'] = 'some value';
Finally, you may want to use session_status() while debugging to verify you've actually started the session correctly (http://php.net/manual/en/function.session-status.php).

Categories