Securely Pass/Retrieve Referrer Page in PHP via GET?

822 views Asked by At

I have read several posts pertaining to redirecting to the previous page upon user action login/etc. and most mentioned that getting the previous page url via HTTP_REFERRER is non-reliable/insecure.

My question is, could I append a bit of info to the end of the URL say, login.php?referrer=main or login.php?referrer=prof, and rely on such variables to not be spoofed, CRSF'd, altered in any way?

Would POST be better/worse? Is there any reliable/secure way to achieve what I am after?

Basically, I am trying to find the best way to get the referring page in PHP so that it can be redirected to without the risk of malicious intentions causing site malfunctions.

TIA.

EDIT: Scenario:

A user visits a comment page, but needs to be logged in to post a comment, so a login to comment link would be placed on the page. When the user clicks the login to comment link, its target would be login.php?comment20303, upon visiting the login page and supplying verified credentials, they should be taken back to the comment20303 page they originated from prior to logging in.

REEDIT: My question boils down to, is appending the redirect url to the login page, accessing it via GET, and re-using it to return them to the original page secure? It seems from the comments below that the answer is no, not without some validity checks.

1

There are 1 answers

8
silversunhunter On

Often I will place the referring page into a hidden field in my form

<input type="hidden" name="ref" value="login.php"/>

Then in my target page I will use the referral with get variables set to tell the login page why it has been re-directed back

$ref = trim(strip_tags($_POST['ref']));

//something causes an error (incorrect password maybe)======
$error = "true";
$msg = urlencode("Login Incorrect");
//no harm in putting the referring page in the GET but I don't think you need it for a login process.
header('location: '.$ref.'?error='.$error.'&msg='.$msg);
die();

Back in the login page I will handle the error if it is set which tells me I came from the form target and there was an error

if (isset($_GET['error']) && $_GET['error'] == "true"){
    $error = true;
    $msg = trim(strip_tags($_GET['msg']));

//Echo out the msg if it is set somewhere in your HTML
}

I prefer to use POST when submitting a form. GET is easiest to use for a re-direct.

EDIT: BASED ON YOUR COMMENT

  1. user is entering comment and the comment has a system generated id.
  2. user is not authenticated so is redirected to reg/login with ID in URL
  3. user registers/logs in again pass the ID in URL
  4. system authenticates and because thereis a $_GET['commentID'] it inserts a db entry associating the user to the comment
  5. return user to the comment editing area with ID in URL and handle.

Always trim and strip the GET