Helen Neely
Helen Neely

Reputation: 4740

Script Redirecting Even when valid

This is a little script that supposed to redirect if someone came from a different page, but it's does not work. It keeps redirecting to the form page.

Here's the code

<?php

define('FORM', 'form.html');
$referer = $_SERVER['HTTP_REFERER'];

// this keeps redirecting even when I came by submiting the form to this page
if ( $referer != FORM ) {
   header('Location: ' .FORM);
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing 123</title>
</head>

<body>
  <?php
        $name  = $_GET['name'];
        $surname  = $_GET['surname'];
        echo 'hello'. $name. 'nice to see you here mr' .$surname;
    ?>
</body>
</html>

Upvotes: 0

Views: 40

Answers (2)

dbrumann
dbrumann

Reputation: 17166

I suppose what is causing you trouble, is that you don't exit the script after calling header():

header('Location: ' . FORM);
exit;

Anyway you should consider checking for the required parameters, instead of relying on $_SERVER['HTTP_REFERER'], as sending the referrer-info may be disabled in the user's browser.

isset($_GET['name']) : $name = $_GET['name'] ? $name = null;
isset($_GET['surname']) : $surname = $_GET['surname'] ? $surname = null;

if (empty($name) || empty($surname)) {
    header('Location: ' . FORM);
    exit;
}

Additionally you should escape $_GET['name'] and $_GET['surname'] before outputting it!

Upvotes: 1

busypeoples
busypeoples

Reputation: 737

You could test if the user came from the "form page" by checking if a certain $_POST variable has been sent. For example you could try something like

if(isset($_POST['somehiddenvalue']) && $_POST['somehiddenvalue'] == $hiddenVal) {
   // ok.
} else {
   // redirect
}

The user will still be able to manipulate the Post variables, keep this in mind.

Upvotes: 1

Related Questions