简体   繁体   中英

PHP variable scope through a header:location redirect

When redirecting using header: location how can I pass a variable along with this redirect?

For example, I have a value stored in $username in my function.

Part of the function:

if(register($email_address, $username, $password) === true){

    // Sends an email
    send_email($email_address);

    // Reroute to success page
    $succeeded = true;
    header('Location: register-success.php');
}

Then on register-success.php I wish to output the username onto the page:

<?php 
echo $username;
?>

But when I do this I don't get an error, just a blank missing variable output where the echo is.

Just append it and send it..

if(register($email_address, $username, $password) === true){

    // Sends an email
    send_email($email_address);

    // Reroute to success page
    $succeeded = true;
    header("Location: register-success.php?username=$username"); //<--- Here
    exit; //<-- Add this too
}

and on your register-success.php page..

<?php 
echo $_GET['username'];
?>

Try using a session variable. In your first script add

session_start(); to the top of the page.

and to the top of every other page which needs to use a session variable.

you can then set things like $_SESSION['username'] . These will be avaiable to every script in the same session, eg until the user closes their browser.

the benefit of this over using $_GET is that it's transparent to the browser, and therefore more secure.

If you want me to post more info about this (or anyone else for that matter), I'd be happy to do so.

The simplest way is to use a GET request:

header('Location: register-success.php?username='.$username);

You can then retrieve the the variable using the superglobal $_GET['username']

ex. (in your register-success.php)

$username = $_GET['username'];
echo $username;

I know, based on your other questions, that you're going session-crazy. So why not use sessions here? For example, I know that your register page uses SESSION['status']['register']['error'] so why not use something like SESSION['values']['username'] By doing it like this, you prevent somebody from pausing your request, switching the username and then displaying a different username and potentially (depending on how your code is structured) a different profile.

Then you just have to structure your register success page like such:

<?php
session_start();
echo $_SESSION['values']['username'];
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM