Dan382
Dan382

Reputation: 986

Using PHP to return to page after form post

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.

Upvotes: 1

Views: 3586

Answers (2)

Shijin TR
Shijin TR

Reputation: 7756

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();
?>

Upvotes: 2

vitorsdcs
vitorsdcs

Reputation: 692

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.

Upvotes: 1

Related Questions