views:

109

answers:

5

Hi guys, I need to make an authentication script in php. I have already made a login.php page, where the user can enter his unsername/password and it gets checked against a database. If the unsername/password are correct, the user should be forwarded to members.php page together with a $_SERVER['username'] variable.

What is the command in PHP to go to another webpage, in this case members.php ?

in pseudocode I see it like this:

if ( unsername/password are OK ) { $_SERVER['username'] = $username; goto(members.php); }

Thanks!

+2  A: 
header('Location: members.php');

Remember that headers must be sent before any output is sent.

nuqqsa
+4  A: 

You can't set anything $_SERVER. You should use a session + cookies instead. Then you can let the client know to go to members.php using the Location header:

session_start();
$_SESSION['username'] = $username;
header("Location: members.php");
exit(0);
Wim
Thanks, got it working!
`start_session` is incorrect. The correct name is `session_start`
Jacob Relkin
@Jacob Thanks, fixed it.
Wim
+1  A: 

You should most definitely use sessions in this instance.

Here's an example:

session_start();
$_SESSION[ 'username' ] = $_POST[ 'username' ];
header( 'Location: members.php' );

exit();
Jacob Relkin
+2  A: 

The code to redirect a user through PHP (provided you have not yet sent any output to their browser) is header( 'Location: members.php' );.

As an aside, you are probably wanting to use $_SESSION[] as opposed to $_SERVER[]

Lucanos
A: 

@nuqqsa headers can be sent even after you sent body content if you use output buffering. You can do that by editing php.ini setting output_buffering = On or by calling the output buffering functions at runtime

Andreas M.
Please use comments rather than creating a new answer.
Neil Aitken
You're right here, certainly to be considered in case you really need to send your headers after output has started (yet a bad practice if the purpose is to ignore possible previous notice/warning outputs, then please properly implement error handling).
nuqqsa