views:

42

answers:

1

Hi! This is a quite weird and annoying problem, which is reproduced with the script below.

  1. Say we have two pages: script.php and script.php?second.
  2. Page 1 creates some database entries and redirects to page 2.
  3. On page 2, the user is presented with an editor for said entries.

If page 1 for some reason crashes on the first try, and prints some error message, a strange thing will happend. If we refresh page 1 (and this time it redirects fine), every consecutive refresh (of page 2) will actually refresh page 1 and again redirect to page 2.

In the above example this would create new database entries for every refresh, which is the problem I want to circumvent by redirecting to page 2.

<?php

header('Content-type: text/plain');

session_start();

if (!isset($_GET['second'])) {

    $_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter'] + 1 : 1;
    /*$_SESSION['counter'] = 0;
    exit('asd');*/
    header("Location: {$_SERVER['PHP_SELF']}?second", true, 303);
    exit;

}

echo "Counter: {$_SESSION['counter']}";

To try the above complete script, first run it with the commented code intact, then by enabling the commented code.

I've tried 301, 302 and 303 redirections. Does someone know why this is happening?

+1  A: 

You're checking if the get variable second is set. Yet you have not set it on your redirect.

Try

header("Location: {$_SERVER['PHP_SELF']}?second=1", true, 303);
Damon Skelhorn
Correct - from PHP online manual, isset "Determine if a variable is set and is not NULL" so you need to give second a value.
Ronaldo Junior
?second works, that is not the problem :) ?second sets $_GET['second'] to an empty string.
Znarkus