开发者

PHP header and $_SESSION

I'm currently building a CMS and I'm having an issue with PHP sessions:

  • Anywhere on my website user can start CMS by adding query string to URL -> ?mod=admin
  • ?mod=admin will redirect to login.php
  • After authentication I would like to redirect user to page he came from with CMS functionalities enabled

For that I store current page url in a session before user go to login.php

url.class.php script

function curPageURL() {
 session_start();
 $pageURL = 'http';
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["PHP_SELF"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"];
 }
 $_SESSION['url'] = $pageURL;
}

Login.php script: if validation successful I start a session and TRY to redirect user to page he came from:

if($num_row开发者_JS百科s == 1){
  session_start();
  $_SESSION['username'];
  header('Location: ' . $_SESSION['url']);
}

I get a "session had already started" error.

But if I redirect to a specific page (homepage for instance) then all is working fine. for instance -> header('Location: index.php');


If thats the error you are getting then you need to check to see if you've already started the session somewhere else. In which case you need to put:

if(!isset($_SESSION)){
    session_start();
}

In place of where you put your normal session_start().


Can you not just redirect to the previous page using $_SERVER['HTTP_REFERER']?

What actually happens when you try to run your script in it's current state?


In url.class.php, has you already started the session? Your problem could be that you haven't started the session, and hence no session data can be stored.

In your url.class.php try checking that the session variables hold the values that you want.


Anywhere on my website user can start CMS

I assume you mean that the website is implemented via a CMS and that the user can gain access to elevated privileges / additional functionality at any stage by appending to the query string.

store current page url in a session

Erk.

This is not the right place to store this information - it should be passed via the URL (or via POST - but that's not going to work across redirection):

session_start();
if (!is_auth_for_cms() && $_GET['mod']=='admin') {
     // simplified a bit...
     $comeback='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
     // rewriting the get trigger avoids short circuit looping problems
     $comeback=urlencode(str_replace('mod=admin', 'mod=auth', $comeback));
     header("Location: " 'http://' . $_SERVER['HTTP_HOST'] . "/login.php?backto=$comeback";
}

Leaving aside the typos in your code, what is the question?

if($num_rows == 1){
  session_start();
  $_SESSION['username'];
  header('Location: ' . $_SESSION['url']);
}

What do you think the third line does?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜