andychukse
andychukse

Reputation: 153

How do I retain value of a variable after exit() function in PHP

Please what is the best way to get the new value of a variable after the exit function in php. My script below is a sample, I want to get new value of variable $ee and use it to echo an error message after calling exit function.

$ee = 0;
$required = array('name', 'location', 'email', 'school', 'age');

if(isset($_POST['name'])){

    foreach($required as $ff){
    if(empty($_POST[$ff])){
    header("location:register.php");
    $ee = 1;
    exit($ee);          
    }
    }

    }

Upvotes: 0

Views: 2052

Answers (3)

Phil
Phil

Reputation: 11175

The easiest way to keep that variable alive is through PHP $_GET, example:

foreach($required as $ff){
    if(empty($_POST[$ff])){
        $ee = 1;
        $encoded_ee = urlencode($ee);
        header("location:register.php?error=" . $encoded_ee);
        exit($ee);          
    }
}

Upvotes: 1

hsz
hsz

Reputation: 152206

There is register_shutdown_function function which allows you to register function that will be called when exit event rises.

void register_shutdown_function ( callable $callback [, mixed $parameter [, mixed $... ]] )

Registers a callback to be executed after script execution finishes or exit() is called.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

Upvotes: 1

Quentin
Quentin

Reputation: 943100

If you exit then the script has finished and can't do anything else without being executed again.

echo the error message (not to STDOUT since you are redirecting) before you call exit.

If you want to use the data in the variable after the script has finished, then you have to store it somewhere where it will persist and then read it back when the script (or a different script) is executed in the future.

Possible places you might store it are:

  • A cookie
  • A session
  • A database
  • Via a webserver
  • In a file (don't use a file, you have to deal with race conditions and file system inefficiencies, use a database server instead so all that is taken care of for you)

Upvotes: 1

Related Questions