0

I'm using a form that posts to a PHP script. This then set's a cookie and returns users to the homepage:

HTML form:

<form action="update.php" method="post">
  <select name="choice">
    <option value="style1" selected>1</option>
      <option value="style2">2</option>
      <option value="style3">3</option>
    </select>
  <input type="submit" value="Go">
</form>

PHP:

<?php 
  $year = 31536000 + time();
  setcookie('style', $_POST['choice'], $year);
  header('Location: index.php');
  exit();
?>

I want to change the behaviour of this script to redirect users to page the form was submitted from.

I've tried adding the following to the form:

<input type="hidden" name="goback" value="<?php echo($_SERVER['REQUEST_URI']); ?>">

However I'm unsure how best to change my PHP 'location' to utilise this echo request.

Dan382
  • 976
  • 6
  • 22
  • 44
  • Look at this http://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php – Dan Aug 20 '14 at 13:15
  • 1
    Is there a reason you're not using the originating form page as the action for the form? Just check for $_POST, do your PHP processing, then display the form again. – Pagerange Aug 20 '14 at 13:18

2 Answers2

1

Try changing this line

header('Location: index.php');

For this one

header('Location: ' . $_SERVER['HTTP_REFERER']);

It should send users back to the page where they came from.

vitorsdcs
  • 682
  • 7
  • 32
  • There's no rock solid guarantee though that any HTTP Header (including Referer) will actually exist in the request. – CD001 Aug 20 '14 at 13:40
  • In OP's case it will always exist, won't it? – vitorsdcs Aug 20 '14 at 13:42
  • Not necessarily, the HTTP REFERER is sent by the browser - it can be blanked, garbled or spoofed. `$_SERVER['HTTP_REFERER']` is simply what the server received from the client. – CD001 Aug 20 '14 at 13:44
1

Try this,

<form action="update.php" method="post">
 <select name="choice">
   <option value="style1" selected>1</option>
   <option value="style2">2</option>
   <option value="style3">3</option>
 </select>
 <input type="hidden" name="goback" value="<?php echo $_SERVER['REQUEST_URI']; ?>">
 <input type="submit" value="Go">
 </form>

PHP update.php

<?php 
    $year = 31536000 + time();
    setcookie('style', $_POST['choice'], $year);
    header('Location:'.$_POST['goback']);
    exit();
?>
Shijin TR
  • 7,516
  • 10
  • 55
  • 122