8

I'm using a function for login.

But when i change the page from my website, i have to login again.

how can i keep my user logged in when i change my page?

Here my code:

<?php
error_reporting(0);
if($_POST['login']=="") {
?>
  <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
    <label><a>Utilizador</a><input type="text" name="login" id="s-user"></label>
    <label><a>Senha</a><input type="text" name="password" id="s-pass"></label>
      <input type="submit" class="submit" value="Entrar">

  </form>


<?php
}
else {
?>
<?php
include("classes/Utilizadores/Cliente.class.php");


        if($_REQUEST['login']!="") {
            if($_REQUEST['password']!="") {

                            $clientes = new Cliente();
                            if($clientes->verificarCliente($_REQUEST['login'], $_REQUEST['password'])) {
                                echo "<br>";
                            } else {
                                echo "<br><a>Login ou senha errados, caso não tenha, <a href='criarconta.php'> registre-se</a>, <a>ou</a> <a href='index.php'>volte a tentar.</a></a><br>";
                            }
                            $clientes->endCliente();

            } else {
                echo "ERRO: Deve introduzir a sua password...<br>";
            }
        } else {
            echo "ERRO: Deve introduzir o seu login...<br>";
        }

}
?>

My function code:

function verificarCliente($login, $password) {
    $sql = "SELECT * FROM users WHERE login LIKE '$login' AND password LIKE '$password'";
    if(($rs=$this->bd->executarSQL($sql))){
        if(mysql_fetch_row($rs)==false) {
            return false;
        } else {

                                echo "<br><b> <a>Bem-Vindo <font size=2>" .mysql_result($rs,0,"login")."</font></b></a><br><br><br>";     

            return true;

        }
    }
    else {
        return false;
    }
}
robbmj
  • 16,085
  • 8
  • 38
  • 63
user2744048
  • 111
  • 1
  • 2
  • 7
  • 3
    You can use [`sessions`](http://www.php.net/manual/en/features.sessions.php) Plus, if you will be using sessions, remember to have `session_start();` inside all your pages. – Funk Forty Niner Dec 14 '13 at 16:12
  • 1
    How do you know this much php, and never heard of sessions? – samayo Dec 14 '13 at 16:14
  • Im learning how to use classes, this code is from my teacher, and im building a project based in this code. My difficult is to use sessions in functions. Because i have heard about sessions, and i used sessions on my last project(without functions and classes), but i dont know how to use sessions in functions. – user2744048 Dec 14 '13 at 16:18
  • Then I suggest you start Googling and testing. – Funk Forty Niner Dec 14 '13 at 16:19
  • 1
    Indeed. The OP's teacher is obviously unaware or ignorant of the `mysql_` functions' deprecation. @Qǝuoɯᴉs – Funk Forty Niner Dec 14 '13 at 16:23
  • You can place/use sessions (almost) anywhere, depending on when you want the session to start. – Funk Forty Niner Dec 14 '13 at 16:27
  • @bivoc while I agree with you, your comments are relatively unconstructive. Please consider rewording them in a way so that they help rather than hurt. Case in point: Fred's comments above. – dudewad Oct 29 '14 at 13:12

4 Answers4

5

Use $_SESSION Variables. http://www.php.net/manual/en/reserved.variables.session.php. They help you store variables you can access them from any other part of the website.

On login success:

1) Query basic info like first name, last name, sex, birthday etc.

2) Save them in variables such as $first_name, $last_name etc.

3) Assign those variables to sessions like this:

$first_name = $_SESSION['first_name'];
$birthday = $_SESSION['birthday'];

On logout, simply destroy the session with session_destroy().

So $_SESSION['first_name'] would be the first name of the user that can be manipulated from anywhere on the code.

EDIT: I quoted php.net instead of W3 school because a lot of people don't seem to like it.

Eisa Adil
  • 1,743
  • 11
  • 16
  • 1
    Sessions are not stored client side. Session data is stored on the server. The session id is stored as a cookie on the client, which will be sent to the server on each request. – aziz punjani Dec 14 '13 at 16:17
  • 2
    dont recommend w3schools as a reference to learning about php. The site is not very accurate – samayo Dec 14 '13 at 16:18
  • @Qǝuoɯᴉs Point noted. Thanks, even though I learnt all my basics from W3 schools. – Eisa Adil Dec 14 '13 at 16:22
  • 2
    @bivoc after reading your thoughts about w3schools, my whole life looks a lie to me. – Asad Ullah Jul 03 '14 at 19:16
2

You are not saving the state of a user. You should save the state of a user in a session and retrieve on the next page.

Please review http://www.w3schools.com/php/php_sessions.asp

Asad Ullah
  • 2,257
  • 2
  • 24
  • 23
2

First off I would highly recommend not using the LIKE operator, use the = operator instead. Also I would recommend using parametrized quires. Also I would recommend hashing your user's passwords, salting them is a very good idea too.

Give these pages a read. There is good information here:

How can I prevent SQL injection in PHP?

Secure hash and salt for PHP passwords

crackstation.net supplies a free library for multiple languages and a good explanation.

But you need to keep track of the logged in user:

function verificarCliente($login, $password) {

        $sql = "SELECT * FROM users WHERE login = '$login' AND password = '$password'";
        if(($rs=$this->bd->executarSQL($sql))){
            if(mysql_fetch_row($rs)==false) {
                return false;
            } else {
                session_start();
                $the_username = // grab the username from your results set  
                $_SESSION['username'] = $the_username; 

                // put other things in the session if you like
                echo "<br><b> <a>Bem-Vindo <font size=2>" .mysql_result($rs,0,"login")."</font></b></a><br><br><br>";     

                return true;

            }
        }
        else {
            return false;
        }
    }

Now on other pages that require a user to be logged in

session_start();
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
      // redirect to your login page
      exit();
}

$username = $_SESSION['username'];
// serve the page normally.
Community
  • 1
  • 1
robbmj
  • 16,085
  • 8
  • 38
  • 63
0

Add in your config.php file:

$_SESSION["fullname"]=$name;

Others pages where you want to keep your user logged in:

<?php 
    if(!isset($_SESSION["fullname"]) || empty($_SESSION["fullname"])) 
    {
?>
     <li><a href="/starks/login.php" class="active">Login</a></li>

<?php 
    }
    else
     {
?>
      <li><a href="/starks/login.php" class="active"><?php echo $_SESSION["fullname"] ?></a></li>
<?php 
     }
?>
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29