Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect if user already logged in

I have a login script that does this:

$_SESSION['username']=$username;

$_SESSION['password']=$password;

If the user logged in succesfully. And so I edited the signup page to do this:

<?php

function redirect() {
    header(' URL= index.php');
}

?>
<?php session_start(); ?>  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" id="jmtoday" class=" no_js">
<head>
 <link href='icon.jpg' rel='icon' type='image/jpg'/>
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta http-equiv="Content-language" content="en" />
 <LINK REL=StyleSheet HREF="Mainstyles.css" TYPE="text/css"></link>
 <Title>Sign up | JMToday</title>
</head>
<body>
<?php
  if(isset($_SESSION['username'])){
   redirect();
  }
?> 

But it doesn't redirect the user when I logged in with my account that I created. Why is that?

like image 896
Samir Ghobril Avatar asked Dec 24 '10 10:12

Samir Ghobril


2 Answers

header(' URL= index.php');

should be

header ( 'Location: index.php' );

Also you might want to put a die() statement after the call to header() so that you stop the execution of your script completely.

And you should probably move the call to redirect() above any other output since HTTP headers must be the first thing in the response. It's possible that this is also the cause of your problem.

like image 185
Jan Hančič Avatar answered Oct 15 '22 19:10

Jan Hančič


Change the redirect() function to:

header('Location: index.php');

And move the call to redirect above all the html output:

<?php session_start();
if(isset($_SESSION['username'])) {
    redirect();
} ?>

From the header() docs:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

This is what it should look like in the end, taking @Jan's advice to add a call to die():

<?php
function redirect($DoDie = true) {
    header('Location: index.php');
    if ($DoDie)
        die();
}
php session_start();
if(isset($_SESSION['username'])) {
    redirect();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" id="jmtoday" class=" no_js">
<head>
 <link href='icon.jpg' rel='icon' type='image/jpg'/>
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta http-equiv="Content-language" content="en" />
 <LINK REL=StyleSheet HREF="Mainstyles.css" TYPE="text/css"></link>
 <Title>Sign up | JMToday</title>
</head>
<body>
?> 
like image 35
moinudin Avatar answered Oct 15 '22 19:10

moinudin