开发者

How do I continue a session from one page to another with PHP

Ok I set up a session... but now how do I make it work on my other pages?

I tried doing

@session_start();
开发者_Go百科
if(isset($_SESSION['$userName'])) {

 echo "Your session is running " . $_SESSION['$userName'];

}


If your PHP setup is clear (session writing ok) and cookie normally sent to browser (and preserved), you should be able to do something like this

On first page :

session_start();
$_SESSION['userName'] = 'Root';

On a second page :

session_start();
if(isset($_SESSION['userName'])) {
  echo "Your session is running " . $_SESSION['userName'];
}

Be careful session_start() must be called before any output is sent, so if you had to use the @ for session_start it can hide warnings.

As these are warnings, if given example doesn't work try to add this before calling session_start :

error_reporting(E_ALL);


On the first page (test1.php),

<?php
session_start();

$_SESSION['userName'] = 'This is Ravi';

?>

On the second page (test2.php),

<?php
session_start();
if(isset($_SESSION['userName'])) {
echo "Your session is running " . $_SESSION['userName'];
}

?>


Make sure session_start() is at the top of every page you wish to use sessions on. Then you can refer to session variables just like in your example.


Check that the session cookie is being sent to the browser on the first hit and getting returned by the browser in subsequent requests. There are lots of reasons why this may be failing - typically PHP has flushed the headers before the call to session_start() (which may be due to UTF-8 BOM chars or just messy programming).

Make sure you've got error reporting enabled.

C.


Make sure both pages are on the same domain. Even www.site.com is different than site.com

Using echo session_id(); also helps identifying your session_id on each page, make sure there are the same


Be aware of case sensitivity in the $_session name variables.

Therefore $_SESSION['userName'] different with $_SESSION['username'].


  1. Create a login page, the user must not login without correct id and passowrd.
  2. After logging in the user comes to the home, here user can logout and goes back to the login page

NOTE: User must not access home page without going through login page.


first page (hello1.php) - Storing Session

$userName = "Nick";
session_start();
$_SESSION['username'] = $userName;

second page (hello2.php) - Output Session

session_start();
$userName = $_SESSION['username'];
echo "$userName";

Output: Nick

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜