I am new to PHP so have a very basic question
I creating a page I am creating a page initially with user id and password, once user id and password are entered and submit is clicked, AJAX is called to validate that against database.
once validation done I want to refresh the page which show more option to user
I was thinking to use session
but every time I refresh the page a new session is created
I put this at the top of the page as a test and always when F5 is press I see "new session" on top of the page
<?php
if (!isset($_SESSION)){
session_start();
echo("new session");
}
else
{
echo("old session");
}
?>
session_start must be called always before anything related to a session. After calling it, you can get or set values of the $_SESSION variable.
Reference.
Your code should be:
<?php
session_start(); // always call this at top
if (!isset($_SESSION['has_been_here'])){
$_SESSION['has_been_here'] = true;
echo("new session");
}
else
{
echo("already been here");
}
?>
From php.net:
session_start — Start new or resume existing session
That means you have to start your session with
session_start();
on every page, in the first line, which will start or resume it. Check the php.net manual, it will help you understand how to handle and check sessions correctly.
Related
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>
I have a page where, after a user logs in, the session starts and there is a welcome message with the User's Name - like so:
<h2>Welcome, <?php echo $_SESSION["User"]; ?>, to the site!</h2>
Or something along those lines - haven't decided, yet.
But the problem is, is that it doesn't show up.
I have the code that authenticates the user and all that, and that portion works.
They authenticate and they have a session - it DOES exist (if not, the page would redirect them to the login or the error page depending on how many tries).
When they authenticate, the form posts to a "login.php" where all the other code happens, including this:
if (isset($_POST['submit']) && ($allowEntry == yes))
{
session_start();
session_register ("Logged_In");
session_register("User");
$_SESSION["Logged_In"] = 'true';
$_SESSION["User"] = $user;
if ($_SESSION["User"]=='SOMEUSER')
{
header( 'Location: /somepage.php' );
exit;
}
elseif ($_SESSION["User"]=='SOMEOTHERUSER')
{
header( 'Location: /someOtherPage.php' );
exit;
}
}
So, does anyone know how to make that text appear in the "" element above?
I'm not sure I completely understand the question, but I gather that you're setting the session in one script and trying to obtain a value from it in another? If so, it's most likely because you haven't called session_start() in the second. Note from the docs
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.
1: i use register.php to sign up the clients,
2: the data collected from the form is send to 1.php, it is saved in database
3: after form data is saved in database, 1.php forwards selected form data (myValue) to register.php?myValue='abc'
in 1.php, i am saving a session variable like this
#session_start();
$_SESSION['color']='blue';
the code of register.php is
if (isset($_SESSION['color'])) {
header('Location: http://mydomain.com/thankyou.php');
}
else {
#session_start();
some other stuff that was initially use for signing up the clients
my logic is to check for session variable and to redirect it to some-other page
when step 1 , step 2 and step 3 are complete, page should be
redirected to thankyou.php
currently, when step 1, step 2, step 3 are done, instead of opening thankyou.php, the following page is being opened
http://mydomain.com/register.php?myValue='abc'
however, if i re-open register.php or go back to step one (opening register.php), thankyou.php is displayed...
can somebody guide me where i am doing the blunder? why redirection is not being successful although session variables are being created?
code Update
i tried the following code at the top of my register.php
#session_start();
if (isset($_SESSION['color'])) {
header('Location:http://mydomain.com/thankyou.php');
exit;
}
else{
remaining stuff
it occasionally do the trick, redirects to the page, while on occasion (greater in number), it fails in redirecting to thankyou.php,, also the code needs to delete complete history and cache to work (after doing so, still miss hits occurs..)
Make sure you use exit(0); right after you do a header redirect otherwise php will still parse and run the rest of your script, sometimes it can cause some funny behaviour.
In your register.php, you can't test for the session variable before you issue the session_start, so your code should be more like:
session_start();
if (isset($_SESSION['color'])) {
header('Location: http://mydomain.com/thankyou.php');
}
else {
// Something else....
EDIT:
Another thing I've found useful when trying to set session variable in conjunction with redirects is to proceed to the redirect only after running a function. Here's how it would work:
$throwAwayVariable = setColor('blue');
if($throwAwayVariable ){ // separated out into a function so it wouldn't redirect before the session variable was saved
session_write_close();
header("Location: http://mydomain.com/thankyou.php");
}
function setColor($color){
#session_start();
$_SESSION['color']='blue';
return true;
}
Since not all your code is posted, you'll have to figure out where this goes, but I've always had my session vars work after this process.
Your session_start() call in register.php needs to be BEFORE you call any $_SESSION variables.
I have the same issue, then I try to add session_start and session_write_close, and it works!
session_start();
$_SESSION['status'] = 'Updated Poem successfully';
session_write_close();
header("location: index.php");
I have a system where the user logs in and is immediately directed to a PHP page that runs some queries which it inputs into session variables. After the PHP has finished executing, it redirects the user to the main page. I would like to know how I can set it up, so that when the user refreshes the main page, it redirects them to the preceding page where the calculations can run again before the main page is displayed. I simply cannot have the two pages merged together. Does anyone know how I can accomplish this?
EDIT: PHP include is the closest to what I need, but the problem is that when I use AJAX to submit a form, the session variables in the first file update with new data from the database. Those variables need to stay static until an actual page refresh by the user. Does anyone know how I can include the form but make it invisible to Jquery?
You could store a value to the $_SESSION and every other load, forward to the other page.
// Start session
session_start();
// If the session variable is set...
if (isset($_SESSION['loadCount']) {
// Increase the count
$_SESSION['loadCount']++;
// If it is even...
if ($_SESSION['loadCount'] % 2) {
// Reidrect
header('Location: /calculate-again.php');
die();
}
} else {
$_SESSION['loadCount'] = 1;
}
In the login form, make it submit to page_with_awesome_calculations_and_queries_to_session_variables.php. Assuming no input is sent in that page, make your calculations queries and sessions there, and then send a Location header to the new page.
header('Location: 'index.php');
This will cause the address bar in the browser to actually change to index.php, and a refresh will make the user stick there.
You should also secure your page_with_awesome_calculations_and_queries_to_session_variables.php to not allow access unless the correct $_POST variables are set.
Have mainpage.php receive one url parameter t which is the epoch timestamp.
Whenever calculation.php redirects to mainpage.php it will pass the epoch timestamp. If mainpage.php finds the epoch timestamp is older than five seconds, it will redirect back to calculation.php and exit.
mainpage.php
if (time() - $_GET['t'] > 5)
{
header('Location: calculation.php');
die();
}
else
{
// proceed normally
}
calculation.php
// perform calculation
header('Location: calculation.php?t=' . time());
Add
<?
require 'calculations.php';
// Mainpage goes here
?>
to the top of the mainPage. This makes it an extension of the mainPage which is run before the main page is loaded.
Please review this Stackoverflow post.
I have the same PHP problem as bob_cobb. Here's Brad Chrisite's answer:
Order of operations.
Place your session creation and
test-for-validity check at the very
top of the page so the rest of the
page can make judgment calls off the
existence of $_SESSION['username']
(Chances are you're trying to validate
them inside the content area so your
"yay" or "ney" message appears in the
desired section of the document.
Pretty, yes, but the whole top-half of
the page can't see that it's
[potentially] a valid session.)
He is basically saying that session_start() and the conditionals that check for session variables should be at the top, so that the rest of the page could act based upon that.
However, my session-check is at the top of the page.
<?php
session_start();
if ($_SESSION['username'])
//User is already logged in, echo the log out button.
...
else
//User is not logged in, echo the log in form & button.
...
//Login form validation if user is not logged in and submitted form.
//At the end, create session variable ($_SESSION['username'])
//Destroy session if user pressed log out button.
session_destroy();
?>
Everything works fine, but, as with the poster of the other question, I have to refresh my page, to get the top script executed (the script that checks for $_SESSION['username']).
Why is that?
Do not echo anything before your entire control flow is finished. What I mean by this is that you should work to separate logic from display (even better: use a pattern like Model-View-Controller). In your case, maybe you can do something like this:
<?php
/* Place all your control logic at the beginning.
Do not echo anything in this block. */
session_start();
if ($_SESSION['username']) {
$loggedin = true;
} else {
$loggedin = false;
...
//Login form validation if user is not logged in and submitted form.
//If login succeeded, set $loggedin to true.
//At the end, create session variable.
}
//Destroy session if user pressed log out button.
session_destroy();
/* Only display logic below, we do not change any state here */
if($loggedin) {
echo logout button
} else {
echo login form
}
?>
The answer is simple. You need not unset the session after making the user registration.
Try this
<?php
session_start();
if ($_SESSION['username'])
//User is already logged in, echo the log out button.
...
else
//User is not logged in, echo the log in form & button.
...
//Login form validation if user is not logged in and submitted form.
//At the end, create session variable.
//Destroy session if user pressed log out button.
//session_destroy();
--- do a redirect or a refresh here ....
?>