Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "header()" php function unset global variables?

I am developing a php script which contains an html form.

If not all fields are filled in the correct way the script will signal an error and redirect back to the same page with the header function setting an error variable to yes with the get method:

header("Location: registration_page.php?error_empty=yes");

my script has an error handling part in which it highlights the fields containing a mistake, but I would like to keep the value of the fields correctly filled.

I am implementing this feature as I found in this other question:

How can I keep a value in a text input after a submit occurs?

but the problem is that when the page reopens the forms will not contain the old values.

My question is: does anybody know if the header function unsets global variables in the $_REQUEST array?

And do you know what kind of solution could I adopt?Maybe sessions?

Thanks in advance,

Matteo!

like image 675
Matteo Avatar asked Sep 01 '11 19:09

Matteo


People also ask

What does header () do in PHP?

The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).

How do you unset a global variable?

If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so. The unset() function has no return value.

Can functions access global variables PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

What is setting response header in PHP?

As we've already discussed, the HTTP response that a server sends back to a client contains headers that identify the type of content in the body of the response, the server that sent the response, how many bytes are in the body, when the response was sent, etc.


1 Answers

$_COOKIES will stay set, but $_POST & $_GET will be destroyed, as the client is moving to a new page. If they need to be retained, they must first be stored into $_SESSION before calling the redirect.

session_start();
$_SESSION['last_post'] = $_POST;
header("Location: http://example.com");
exit();

// On the redirected page, use the stored POST values and unset them in $_SESSION
session_start();
if (empty($_POST) && isset($_SESSION['last_post'])) {
  $post = $_SESSION['last_post'];
  unset($_SESSION['last_post']);
}
else $post = $_POST;
like image 146
Michael Berkowski Avatar answered Oct 02 '22 14:10

Michael Berkowski