1

I'm using the script below for logging in. I'm trying to redirect the users who were succesfully logged in to another webpage (visible only for logged in users), but it redirects everyone - regardless if the username and password are correct. What's should be changed in the code?
page with login form - index.php
the page that I want to redirect to - content.php


Table in my database

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `emailadress` varchar(255) NOT NULL,
  `pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
)

PHP

<?php 
if (isset($_POST['username']) and isset($_POST['password'])){
$name = $_POST['username'];
$pass = $_POST['password'];

$query = "SELECT * FROM `person` WHERE name='$username' and pass='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
}else{
echo "Login failed.";
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hello" . $username . "
";
echo "<a href='logout.php'>Logout</a>";}
?>

HTML

<form method="post" action="content.php" name="login">

<?php
    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>        
        <label for="username">Username:</label><br>
        <input type="text" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" name="password"><br>
        <button type="submit" name="login">Log in</button>
</form>



dirigibleplum
  • 137
  • 2
  • 2
  • 12
  • 1
    Sidenote: It seems like you are storing passwords in plain text, which is strongly advised you do not use, unless you're already using something to the effect of [`crypt()`](http://php.net/crypt) or PHP 5.5's [`password_hash()`](http://www.php.net/manual/en/function.password-hash.php) function (*which I doubt*). Your code is also missing `session_start();` which is required when using sessions. *Plus*, in its present state, your code is open to [`SQL injection`](http://stackoverflow.com/q/60174/) – Funk Forty Niner Mar 21 '14 at 14:38
  • You're using `and pass='$password'` yet your variable is called `$pass` where you have `$pass = $_POST['password'];` and `name='$username'` and you have `$name = $_POST['username'];` no match. – Funk Forty Niner Mar 21 '14 at 14:42
  • oh, my bad, sorry. no wonder it's not working :) thanks for pointing that out! – dirigibleplum Mar 21 '14 at 14:44
  • You're welcome, I posted [`an answer`](http://stackoverflow.com/a/22561923/) below for you to look at. Put a quick tick to close the question then. ;-) – Funk Forty Niner Mar 21 '14 at 14:45
  • I made another addition to my answer below. You have a trailing comma in `PRIMARY KEY (`\``id`\``),` – Funk Forty Niner Mar 21 '14 at 14:54

6 Answers6

1

There is so much wrong with it

First. the action of your form is the protected page meaning that everyone will be redirected there in any case. You want to move your php code to login.php So that login.php looks like

<?php
    session_start();
    if(isset($_POST['username']) and isset($_POST['password']))
    {
        $username = $_POST['username'];
        $pass = $_POST['password'];
        $query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'";
        $result = mysql_query($query) or die(mysql_error());
        $count = mysql_num_rows($result);
        if ($count == 1){
            $_SESSION['username'] = $username;
            header('Location: content.php');
        }
        else
        {
            $msg = "Wrong credentials";
        }
    }

    if(isset($msg) & !empty($msg)){
        echo $msg;
    }
 ?>
<form method="post" name="login">
        <label for="username">Username:</label><br>
        <input type="text" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" name="password"><br>
        <button type="submit" name="login">Log in</button>
</form>

Note removing the action tag from the form - this way the browser will submit the page to itself, i.e. login.php

Your content.php should check that the user is logged in and get the username from the session

<?php
    session_start();
    if(!isset($_SESSION['username']))
    {
        die("You are not logged in!");
    }
    $username = $_SESSION['username'];
    echo "Hai " . $username;
    echo "<a href='logout.php'>Logout</a>";
?>

Remember to call session_start() in your scripts to tell PHP to create/invoke the existing session

Vladimir Hraban
  • 3,543
  • 4
  • 26
  • 46
  • Needless to say, never store password in the database unencrypted – Vladimir Hraban Mar 21 '14 at 14:45
  • Great, a nice thorough answer. Btw, if you want to make additions after you've written a post, just edit them in, rather than making addendums in comments. It keeps everything neat and in one place. – halfer Mar 21 '14 at 15:44
1

You are using pass='$password' yet your variable is called $pass

where you have $pass = $_POST['password']; and name='$username'

and you have $name = $_POST['username']; there is no match.

Sidenote: It seems like you are storing passwords in plain text, which is strongly advised you do not use, unless you're already using something to the effect of crypt() or PHP 5.5's password_hash() function.

Your code is (possibly) missing session_start(); which is required to be included inside all pages when using sessions. Plus, in its present state, your code is open to SQL injection

Use mysqli_* functions with prepared statements or PDO.

mysql_* functions are deprecated and will be removed from future releases.


Another thing I noticed is that your SQL reads as:

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `emailadress` varchar(255) NOT NULL,
  `pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
                    ^ // <- comma
)

Remove the last comma

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `emailadress` varchar(255) NOT NULL,
  `pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)

Here are a few redirection methods:

header('Location: http://www.example.com/content.php');

and if headers are giving you a hard time:

echo "You will be redirected in 5 seconds...";
echo "<meta http-equiv=Refresh content=5;url=http://www.yoursite.com/content.php>";

Another method is to add ob_start(); under your opening <?php tag which works at times.

Example:

<?php
ob_start();
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$name = $_POST['username'];
$pass = $_POST['password'];
...

header('Location: http://www.example.com/content.php');

...
Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • if I have `session_start();` in the included `connection.php` file (see the edited question), should I also have it in the php code in `index.php` - as you wrote it in the last example (with `ob_start();`) ? :) – dirigibleplum Mar 21 '14 at 15:19
  • Just as long as your included file is inside all pages using sessions, yes. As for `ob_start();` that's just an option I mentioned in regards to, if you get an error message stating `headers already sent....` for the redirection. @dirigibleplum – Funk Forty Niner Mar 21 '14 at 15:21
0

To redirect do this:

    header('Location: content.php');
nFinIt_loop
  • 1,463
  • 2
  • 9
  • 12
  • And `exit()` afterwards - PHP will quite happily carry on executing code after a `header`, even if that it not your intention `:-)`. – halfer Mar 21 '14 at 15:43
0

Your form action is content.php. Anyone who submits the form goes to that page because of that. You'd have to make index.php or another separate page process the form in order for access to content.php to be restricted.

cscracker
  • 365
  • 1
  • 3
  • 8
0
  1. You didn't call session_start(); before using session variables.
  2. the form action="content.php" is where your post is submitted not where it will be redirected.

Put session_start(); before you use the session variables and put the redirect in the if block like this:

if($count == 1){
 session_start();
 $username = $_SESSION['username'];
 header("location: content.php");
}

and in your form action put action as index.php

<form action="index.php" method="post" name="login">

you can leave the form action empty if you are not using HTML5

iamsleepy
  • 550
  • 3
  • 7
0

add this

header('Location: home.html'); or header('Location: home.php');
saigopi.me
  • 14,011
  • 2
  • 83
  • 54