开发者

Maintain a PHP session_start() with cookies

I have a PHP code which starts a session using session_start(). Well, after a user is logged in, is brought to profile.php, which shows that user info. But when the user reloads the page, the session is gone. Is there any way I can maintain it an hour for example? I've tried cookies but I don't know how to tell PHP that the session is started already. Thanks!

Profile.php code for cookies and session start:

if(isset($HTTP_COOKIE_VARS['session'])){ 
     session_start();
} else {
    header('Location: index.php');
}

Login code:

session_start();

$_SESSION['pass']  = $password;
header('Location: ../profile.php');
setcookie("session","1",time()+3600,"/");

Code which checks the session:

if($_SESSION['pass'] == $tableArray[0]['password']) {
    $username = $tableArray[0]['name'];
    $avatar = $tableArray[0]['avatar'];
} else {
    header('Location: index.php');
}

I was calling session_destroy() on here:

<li><a href=<?php session_des开发者_运维问答troy(); echo "index.php"?>>Logout</a></li>

And forgot PHP runs before HTML :P that was the problem!


  • you're not calling session_start() again or
  • you're calling session_destroy(); anywhere in file


Technically speaking I found the solution for this.

One thing is already specified change save path string else change the permission of the directory where your session is being stored.

I did this it worked for me.

If your session is stored in session dir then do this:

chmod 777 session/


Try to set session.use_cookies to be on (in php.ini/.htaccess)


You have to say session_start() at the top of every script that needs to know the session data.

The session cookie is really none of your concern, you should consider that an "implementation detail". (The cookie will usually live in the user's browser until the browser exits.)


I suspect you are not calling session_start() again on profile.php.

You must call session_start() on every script that will access the session data.

UPDATE after code posted

Instead of checking for the presence of the session cookie, instead do something like:

// Start the session first
session_start();
if (isset($_SESSION['username'])) {
  // user is already logged in
} else {
    header('Location: index.php');
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜