drhanlau
drhanlau

Reputation: 2527

Redirection / Return Check in PHP

I have a website running in PHP and I have a page (say confirm.php)

And I only want to allow the users who land to confirm.php comes from a page that I specified (e.g. say register.php), may I know is it possible to achieve this?

Regards, Andy.

Upvotes: 3

Views: 490

Answers (5)

alexn
alexn

Reputation: 58962

You can not rely on the HTTP REFERER because users can manipulate it and browsers can refuse to send it.

The only "secure" way would be to set a session variable on register.php and check if that variable is set on confirm.php. Something like this:

register.php:

session_start();
$_SESSION['valid_user'] = true;

confirm.php:

session_start();
if(!isset($_SESSION['valid_user'])) {
    die("You did not come from the page i specified!");
}

However, this will not take into account if the latest page was register.php, BUT that the user have been on register.php.

Because HTTP is stateless, you need to keep track of this at the server level. If you don't have a authenticated user for which you can track all pageviews, this is going to be very hard to implement. How secure do you really need it to be?

Upvotes: 8

mauris
mauris

Reputation: 43619

Because HTTP is a stateless protocol, you will need to store the state information server-side.

One method is to store a key into the PHP Session Store, then pass it during redirection, then check it again.

register.php

<?php
session_start();

// some other code

$_SESSION['stateKey'] = sha1(time() . mt_rand()); // save a randomly created key

header('Location: confirm.php?key=' . $_SESSION['stateKey']);
?>

confirm.php

<?php
session_start();

if($_SESSION['stateKey'] == $_GET['key']){
    // pass, do things here
}

?>

Upvotes: 1

Arda
Arda

Reputation: 6916

use

$_SERVER['HTTP_REFERER']

more info: here

Upvotes: 0

zim32
zim32

Reputation: 2619

Look at $_SERVER['HTTP_REFERREF'] array in you script to detect from wich page this script was invoked

Upvotes: 0

metaforce
metaforce

Reputation: 1377

use the: $_SERVER['HTTP_REFERER'], and redirect it using header or some custom function...

Upvotes: 0

Related Questions