tags:

views:

102

answers:

8

I have written a very very very simple!! script in php. header redirection not working. 1- encoding : UTF-8 without BOM 2- with adding ob_start() the problem is countiueing. What is wrong in my code;

login.php:

<?php  session_start();
   require_once("funcs.php"); 
   db_connection();
   $username = $_POST['username'];
   $password = $_POST['pwd'];
   $submit = $_POST['login'];
   if($submit){
    if (!filled_out($_POST)) {
                echo "please fill all fields";
            }
     else{
        $query = "SELECT * FROM *** WHERE username ='{$username}' AND password ='{$password}'";
        $result = mysql_query($query);
            if(mysql_num_rows($result) == 1){
                 $found_user = mysql_fetch_array($result);
                 $_SESSION['id']  = $found_user['id'];
                 $_SESSION['username'] = $found_user['username'];
                 $_SESSION['password'] = $found_user['password'];
                 setcookie(session_name(), '', time()+86400, '/');
                 header("Location: tst.php");
                 }
                 else{
                    echo "incorrect username or password";
                 }

           }
      }     


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <p>
    <label for="username">
      Username:
    </label>
    <input type="text" name="username" id="username" />
  </p>
  <p>
    <label for="textfield">
      Password
    </label>
    <input type="password" name="pwd" id="pwd" />
  </p>
  <p>
    <input name="login" type="submit" id="login" value="Log in" />
  </p>
</form>
</body>
</html>
<?php 

 db_disconnect();

?>

and tst.php:

<?php session_start();  
  require_once("funcs.php");    
  if (!isset($_SESSION['id'])){
           header("Location : login.php");
         }
 ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table id="structure">
  <tr>
    <td id="navigation">&nbsp;</td>
    <td id="page"><?php echo "welcome"."". $_SESSION['username']; ?></td>
  </tr>
</table>
</body>
</html>

wthit oppening tst.php directly, header() doesnot redirect to login.php

+4  A: 

Try adding die():

  header("Location: tst.php");
  die();

You should always add a die() because a location header is just a request to the browser to change the page. If you don't die(), the rest of the page will still reach the browser, including possibly sensitive data the user is not meant to see.

Pekka
Hi pekka and thanks for attention;I have added die() but there is no any redirecting yet.http://lgn.designer-depot.com/login.php user:yassi pass: 1111
I used firebug and viewed the html in the net tab of the page on submit of that form and it looks like it's outputting three pages worth of login forms. so it's redirecting multiple times, or just printing all the code from login.php three times. you won't see this if you just view source because firefox parse out the extra html tags.
Samuel
Is there a bug in my script? This is very very simple script!!If yes what is wrong?Or is there bugs in php language?...
@jasmine is the query working out? Do you get any error messages when calling `echo mysql_error()` after making the query?
Pekka
@pekka; The query is ok, with "echo mysql_error() " there is no any error message and if you try with wrong username and password it gives error message.
A: 

As well as the other answers, the Location: header should contain an absolute URL, example header("Location: http://example.com/");

fahadsadah
Always good to do, but not a must.
Pekka
+2  A: 

Try removing the space after "Location":

header("Location: login.php");

Please heed my comment about formatting your code correctly as it's extremely difficult to spot anything else that may be amiss.

Andy Shellam
I have editted this. Please give me enough "time" to edit this after commenting!!!
+2  A: 

Check for white space before your opening <?php tags. It's hard to tell from your formatting here whether there is any, but the whitespace will be sent before your code executes, preventing headers. Also check for white space after any closing tags in included files. (better practice is to omit closing tags altogether)

old answer

You're using setcookie() which will send headers, then trying to redirect. You cannot redirect once headers have been sent. (sorry, this was incorrect)

keithjgrant
Not true AFAIK. You can do a header redirect after sending other headers - you just can't output anything in the body.
Pekka
You can't set a header once they've already been sent, which is what outputting in the body does. `setcookie()` doesn't send any headers, *it just sets them* ready for when all headers are sent.
Andy E
+1  A: 

header is not just a php function. It really modifies a part of http header, so it is impossible to have a part of header, then html data, then another header. To make it work, you should put your header at the beginning of the file, before any html output is done.

alemjerus
+1  A: 

The redirection can take a relative or absolute URL. The problem is with the space BEFORE the colon. Try it like this:

header("Location: whatever.php");
Roadmaster
A: 

you need to put an exit() or die() after the header function - otherwise the rest of the script will continue to execute.

kguest
nothing redirecs with die() ...
it won't redirect with die() - you need die() (or exit) after the header(). Otherwise you're just sending HTML straight after the header content and that will be rendered instead of the browser taking heed of the "Location" header that you're sending down to the browser.
kguest
+1  A: 

I guess the redirect works, but you overwrite the Session-Cookie with an empty value. So the tst.php creates a new empty Session and redirects back to login.php.

Try:

// DELETE this line: setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php?".SID);

Importent: header+session always need SID for not loosing the session!

Corrected: Thanks to @Pekka.

Felix
Thank you Felix;Its now redirecting!But :The requested URL /tst.php
Pekka
@Felix, @pekka and everyoneI love you. Now it is working. I have learned alot of things from your answers.