tanasi
tanasi

Reputation: 1804

Setting session var

Here is my PHP code:

<?php
session_start();

if ( !isset($_SESSION['index_visited']) )
{

$_SESSION['page2_visited'] = 1;
$_SESSION['wrong_number'] = 1;

header('Location: index.php');

}
?>

I think that $_SESSION['page2_visited'] = 1 and $_SESSION['wrong_number'] = 1 never get set. Program redirect me on index.php and thats it.

What I have to do to set it?

Upvotes: 2

Views: 147

Answers (4)

tanasi
tanasi

Reputation: 1804

My mistake. This is not place for $_SESSION['wrong_number'], now it is working. Thank you for answers anyway.

Upvotes: 0

the JinX
the JinX

Reputation: 1980

The header('Location: index.php'); overwrites the session setting headers.

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type.

http://php.net/manual/en/function.header.php

So please try: header('Location: index.php', false);

Upvotes: 1

changokun
changokun

Reputation: 1593

i bet $_SESSION['index_visited'] is set. perhaps you want

if(isset($_SESSION['index_visited']) and $_SESSION['index_visited'] == 1) {

remember, if $_SESSION['index_visited'] has been set to 0, that counts as set.

Upvotes: 1

RDL
RDL

Reputation: 7961

It's probably the session doesn't have time to properly save itself before the redirect happens.

Use session_write_close(); to force the saving of the session right before the header redirect.

So it would be:

<?php
session_start();
if ( !isset($_SESSION['index_visited']) ) {
  $_SESSION['page2_visited'] = 1;
  $_SESSION['wrong_number'] = 1;

  session_write_close();

  header('Location: index.php');

}
?>

session_commit() works too. It's just as alias of session_write_close()

Upvotes: 1

Related Questions