Php session before header

PHP: session isn’t saving before header redirect

Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script,80% of the time the problem is register_globals, and use of a equally named variable $userID somewhere (the other 19% is just overwriting in places one doesn’t expect, 1% is unable to write/lock session before redirect and stale data, in which case you could try session_write_close() before the redirect). It goes without saying register_globals should be off :P,One important thing ( which may not be applicable in your case ) is, if the session is being handled using cookie, cookie can be made to be accessible only under certain directory and subdirectories under that. In your case anyhow, subdirectory will have access to the session.,Then, I’m using session_write_close() after the header(‘location: xxx.php’) call to keep session variables for the next request.

I know this is an old toppic but I found the solution (for me). I’ve put a exit after the header.

$_SESSION['session'] = 'this is a session'; header('location: apage.php'); exit; 

Answer by Layla Payne

What would cause a session variable to be unset or not available after a redirect? for example, below is a snippet of code i’m working with. if exit() was not commented, it would display the variable I’m looking for. but once php hits header() and the next page loads $_SESSION[‘flash’] is null ( or, at least when I use print_r() on index.php this is displayed for flash — with no value: [flash] => ). I am starting a session on index.php.,See if adding that right before the redirect fixes the issue, though the exit would probably be a better approach.,Make sure there is a die(); immediately after the redirect statement because otherwise the original php script will still continue to execute in the background whatever code there might be after the redirect. This could be causing a problem with your session.,thanks for the help! die(); right after the redirect worked. I did not realize that the current php script continues to run after header()… this issues makes sense then because many many lines later I’m including another file that checks $_SESSION[‘flash’] and sets it to null. thanks again.

 if($_SESSION['flash'] == null)< if(isset($insert))< $_SESSION['flash'] = "

message 1

"; > else < $_SESSION['flash'] = "

message 2

"; > > //exit($_SESSION['flash']); switch($_POST['submitted']) < case "Save >Finished": header("Location: index.php"); break; default: . . . . >

Answer by Axl Freeman

I’m losing the data in $_SESSION when I do a header redirect. When I walk through this with a debugger I can see all my data in $_SESSION before I exit();,Then I put a breakpoint after the session_start() conditional below and $_SESSION is completely empty. ,So when you create a redirection, a link or whatever, you do this :,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.

Читайте также:  Php post key exists

myaccount.php:

 $docRoot = getenv("DOCUMENT_ROOT"); . 

Answer by Alia Escobar

Session data is written automatically on destroy — and if I terminate the script with an exit; before the return — then data is also saved correctly in the database.,Data is saved when the script finishes in a «normal way» as I already mentioned — it’s only the redirect that causes the problem (I did some additional testing with some ajax calls).,Very interesting. We could probably add a session_write_close call here that should solve the issue.,Even further investigations points to the fact that calling session_write_close() before fastcfgi_finish_reqeust() is a good idea.

public function bazinga() < $this->autoRender = false; $session = $this->request->getSession(); if($this->request->getQuery('next') !== null) < $sval = time(); $session->write('Bazinga.yes',$sval); // GLUE return $this->redirect(['controller' => 'Bazinga', 'action' => 'bazinga', '?' => ['sval' => $sval]]); > echo "
"; echo $session->read('Bazinga.yes'); >

Источник

PHP: session isn’t saving before header redirect

I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database.
My code is as follows:

// session $_SESSION['userID'] = $user->id; header('Location: /subdirectory/index.php'); 

Then at the top of index.php after the session_start() , i have var_dumped the $_SESSION global and the userID is not in there. As i said ive looked through the PHP manual ( http://php.net/manual/en/function.session-write-close.php ) and neither session_write_close or session_regenerate_id(true) worked for me.
Does anybody know a solution?

Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script

Best Solution

I know this is an old toppic but I found the solution (for me). I’ve put a exit after the header.

$_SESSION['session'] = 'this is a session'; header('location: apage.php'); exit; 
Php – How to expire a PHP session after 30 minutes

You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I’ll explain the reasons for that.

session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.

Читайте также:  Kotlin mutable list find

Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.

Furthermore, when using PHP’s default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file’s last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won’t have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.

session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]

Yes, that’s right. This only affects the cookie lifetime and the session itself may still be valid. But it’s the server’s task to invalidate a session, not the client. So this doesn’t help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed.

Conclusion / best solution:

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) < // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage >$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp 

Updating the session data with every request also changes the session file’s modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

if (!isset($_SESSION['CREATED'])) < $_SESSION['CREATED'] = time(); >else if (time() - $_SESSION['CREATED'] > 1800) < // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session and invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time >
  • session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
  • if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you’ll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.
Php – How to make a redirect in PHP

Summary of existing answers plus my own two cents:

1. Basic answer

You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the declaration, for example).

2. Important details

die() or exit()

header("Location: http://example.com/myOtherPage.php"); die(); 

Why you should use die() or exit() : The Daily WTF

Absolute or relative URL

Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.

Status Codes

PHP’s «Location»-header still uses the HTTP 302-redirect code, this is a «temporary» redirect and may not be the one you should use. You should consider either 301 (permanent redirect) or 303 (other).

Note: W3C mentions that the 303-header is incompatible with «many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.

3. Documentation

HTTP Headers and the header() function in PHP

4. Alternatives

You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.

5. Helper Functions

This function doesn’t incorporate the 303 status code:

function Redirect($url, $permanent = false) < header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); >Redirect('http://example.com/', false); 
function redirect($url, $statusCode = 303)

6. Workaround

As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:

Or a JavaScript redirect even.

window.location.replace("http://example.com/"); 

Источник

Оцените статью