0

I have just started working with PHP to try and get a form that will redirect a user based on the redirect URL that is in their database profile. However, the code that I currently have is not working properly. The login form submits and opens the PHP page that is supposed to process the information, but nothing happens after that. I will include all code and a live test for easier solutions.

Live Example: http://previews.justinwidener.com/

HTML CODE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>

<body>

    <form name="custlogin" id="custlogin" action="custlogin.php" method="post">
        <input class="custlogin_input" name="username" type="text" placeholder="Username" /><br />
        <input class="custlogin_input" name="password" type="password" placeholder="Password" /><br />
        <input class="custlogin_sub" name="log_btn" type="submit" value="LOGIN" />
    </form>
</body>
</html>

PHP CODE:

<?php 
session_start();
if ( ($_SERVER['REQUEST_METHOD'] != 'POST') && !isset($_SESSION['username']) ){
    header('Location: $redirect');
}
?>
<?php 
error_reporting(E_ALL); ini_set('display_errors', 1);
    $host="localhost";
    $username="********";
    $password="**********";
    $db_name="************";
    $tbl_name="testtable";

    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $username=$_POST['username'];
    $password=$_POST['password'];

    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);
    $sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
    $result = mysql_query($sql);

    $count = mysql_num_rows($result);

    if($count == 1){
        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;

        $result = mysql_fetch_array($result);

        $redirect = trim($result['redirect']);
        if ($redirect == '') {
            echo "No redirect value was set!";
        }
        else {
            header('Location: $redirect');
            exit;
        }
    }
    else {
        echo "Wrong password!";
    }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Widener Web Designs - Preview</title>
<link href="styles.css" rel="stylesheet" type="text/css" />



</head>

<body>


</body>
</html>

The database is making a connection I assume since no errors are being thrown, but the issue still lies in the failure to redirect. If this is a simple problem, please do not make me out to be a moron. I am trying to learn and have not had any luck getting this to work. Thanks in advance.

  • 1
    Do you have `display_errors` turned on? You should be seeing PHP complain about _"cannot modify header information, headers already sent"_ Always when developing & testing code, use `error_reporting(E_ALL); ini_set('display_errors', 1);` at the top of your script. You are running afoul of a common mistake with `header()`. There must be _no output of any kind_ before a call to `header()`, but you have the start of your HTML markup already written to the output buffer. [See How to fix headers already sent](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Michael Berkowski Mar 22 '15 at 20:29
  • ^ That, and this `if (!isset($_SESSION['username'])) { header('Location: $redirect'); }` - As it stands, `$redirect` is undefined. It's only defined further down your script, so that too will fail once you've moved your `session_start();` on top. Also do `$result = mysql_query($sql) or die(mysql_error());` see if you have additional errors on the SQL side. – Funk Forty Niner Mar 22 '15 at 20:31
  • You can restructure the logic a bit to store the message like `No redirect value was set` into a variable instead of directly to `echo`. Place _all_ the PHP db checking code before the ` ` so the variable is set. Then output the variable inside the HTML block, all of which comes _after_ the closing `?>` tag from the PHP code. – Michael Berkowski Mar 22 '15 at 20:34
  • I uncluded the error reporting line and was presented with this confusing mess: Warning: Cannot modify header information - headers already sent by (output started at /home/wwdadmin15/public_html/previews/custlogin.php:20) in /home/wwdadmin15/public_html/previews/custlogin.php on line 54 – Justin Widener Mar 22 '15 at 20:47
  • @MichaelBerkowski *...was right on the money* ^ ;-) – Funk Forty Niner Mar 22 '15 at 20:48
  • OKAY! So I have something else happening that I believe is dealing with the definition of the $redirect variable, @MichaelBerkowski. I uploaded the newer version of the script to the link and will update the post here in a second. – Justin Widener Mar 22 '15 at 20:52
  • You have a good start reorganizing the code - you've still got a place where you close & reopen PHP tags `?> – Michael Berkowski Mar 22 '15 at 20:58
  • I have got it working now! Thank you guys for steering me in the right direction! This is brilliant! :D – Justin Widener Mar 22 '15 at 20:58

3 Answers3

0

It looks like you have output before calling header. You cannot redirect after output has already been sent. You should be getting an error message that says as much, you may want to confirm that you have error reporting enabled.

Also, two important things:

  • Do not store plain text passwords. Ever. Look into password hashing
  • Do not use the mysql_* functions. Look into mysqli or PDO.
Mathew Tinsley
  • 6,805
  • 2
  • 27
  • 37
0

First of all, your redirection will not work since you already have HTML output before the redirect code.

Secondly, even if the redirect works, your code as it is currently will fail to insert the submitted data and add the 'username' to the session super-global array, because your test if (!isset($_SESSION['username'])) { comes before the code that processes the form submission and creates the $_SESSION['username'] variable. As such, it will always return false, and your users will constantly get redirected.

To fix these issues, remove this code from its current location:

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

and place this replacement code at the top of your file, before the opening <HTML> tag:

<?php 
session_start();
if ( ($_SERVER['REQUEST_METHOD'] != 'POST') && !isset($_SESSION['username']) ){
    header('Location: $redirect');
}

?>

NaijaProgrammer
  • 2,892
  • 2
  • 24
  • 33
-1

write ob_start(); at the top of your code in php script. or use this code to redirect in php window.location.href = 'http://www.google.com'; //Will take you to Google. like

<?php
echo "window.location.href = 'http://www.google.com'";
?>
Manish Prajapati
  • 1,583
  • 2
  • 13
  • 21
  • I would advice against using ob_start as a band-aid to resolving issues with output being sent before headers. It is better to separate your processing from your UI. The same things goes for using javascript redirects. It's just a patch that doesn't address the underlying problem. – Mathew Tinsley Mar 22 '15 at 20:33