Search code examples
phprequestsuperglobals

Why don't I see the request variable I set in the first script?


As I try to retrieve the variable status from the $_REQUEST[] array I set in the first script (and then do a redirect), I see nothing but a warning Undefined index: status. Why is that ?

<?php
        $_REQUEST['status'] = "success";
        $rd_header = "location: action_script.php";
        header($rd_header);
?>

action script.php

<?php
echo "Unpacking the request variable : {$_REQUEST['status']}";

Solution

  • It is because your header() statement redirects the user to a brand new URL. Any $_GET or $_POST parameters are no longer there because we are no longer on the same page.

    You have a few options.

    1- Firstly you can use $_SESSION to persist data across page redirection.

    session_start();
    $_SESSIONJ['data'] = $data; 
    // this variable is now held in the session and can be accessed as long as there is a valid session.
    

    2- Append some get parameters to your URL when redirecting -

    $rd_header = "location: action_script.php?param1=foo&param2=bar";
    header($rd_header);
    // now you'll have the parameter `param1` and `param2` once the user has been redirected.
    

    For the second method, this documentation might be usefull. It is a method to create a query string from an array called http_build_query().