-1

Currently I'm working on a little project for login page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users. i am using php and sql for this. i want also a logout and senf to the index but i can't find te solution. Here is my code.

    <?php
require ('sql_connect.php');
if (isset($_POST['submit'])){   
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
if (!$_POST['uname'] | !$_POST['pass'])
 {
echo ("<SCRIPT LANGUAGE='JavaScript'>
        window.alert('You did not complete all of the required fields')
        window.location.href='index.html'
        </SCRIPT>");
exit();
     }
$sql= mysql_query("SELECT * FROM `login_users` WHERE `username` = '$username' AND `password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
        window.alert('Login Succesfully!.')
        window.location.href='homepage.html'
        </SCRIPT>");
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
        window.alert('Wrong username password combination.Please re-enter.')
        window.location.href='index.html'
        </SCRIPT>");
exit();
}
}
else{
}
?>

this is my control for the correct user and pass. And here is the page i want to go if the user has logged in. homepage.index:

<html>
<head>
</head>
<body>
<center><h1>Welcome user!</h1></center>
 here some text and other stuff.
 <h3>logout here<h3>
</body>

But now i can write www.mysite/homepage.index and i can go to this page without logging in. Can someone explain this?

Thank you.

TM4CH
  • 23
  • 4
  • 2
    Possible duplicate of [safest way to create sessions in php](http://stackoverflow.com/questions/752332/safest-way-to-create-sessions-in-php) – Esteban Rincon Jan 04 '16 at 22:24
  • Echoing javascript for redirects is a bad idea. Use `header('Location: whatever.php');` and STOP using files with .html extensions. They must be PHP to check the session on each page to see if the user should be able to view it. – developerwjk Jan 04 '16 at 22:39

2 Answers2

2

Your question is part of many many available tutorials, did you try to google it first?

  • do not use mysql extension (using mysqli in example)
  • do not redirect via javascript, if you can do it via php
  • do not redirect to html files, when you need to work with php
  • do not store password as plain text (using php5.5+ function to crypt it in example)
  • do not select *
  • do not echo html code
  • use isset before getting value from $_POST, $_GET

Feel free to google everything to know the reasons.


<?php

class Connection //not sure what you have in sql_connect.php, I made this so the example is complete
{

   static function getConnection(){
      if(self::$connection === null)
         self::$connection = new mysqli('127.0.0.1', 'root', '', 'so');
      return self::$connection;
   }

   /** @var mysqli */
   private static $connection;
}

<?php

class UserAuthenticator
{

   function __construct(){
      session_start(); //you need to start session when working with $_SESSION
   }

   function checkLogin(){
      if(isset($_POST['submit'])){
         $username = $this->getPostEscaped('uname');
         $password = $this->getPost('pass'); //no need to escape through mysqli, we do not use it in query

         if($username && $password){
            $userData = Connection::getConnection()->query("SELECT password FROM login_users
               WHERE username = '$username'")->fetch_assoc();

            if($this->verifyPassword($password, $userData['password'])){
               $this->login($username); //storing username for simplicity, but I do recommend to store id or some generated hash even better
               $this->flash('Login succesfull.');
               $this->redirect('homepage.php');
            }else $this->flash('Wrong username / password combination. Please re-enter.');
         }else $this->flash('You did not complete all of the required fields.');

         $this->redirect('index.php');
      }
   }

   function isLogged(){ //actual answer to the question - how to check the logged user
      return isset($_SESSION['logged']);
   }

   function verifyPassword($password, $passwordHash){ //public so you can use it elsewhere
      return password_verify($password, $passwordHash);
   }

   function getPasswordHash($password){ //public so you can use it elsewhere
      return password_hash($password, PASSWORD_DEFAULT);
   }

   function showFlashMessages(){
      if($flashMessages = $this->getFlashes()): ?>
         <script language="JavaScript">
            <?php foreach($flashMessages as $message): ?>
            alert('<?= $message ?>');
            <?php endforeach ?>
         </script> <?php
      endif;

      unset($_SESSION['flashmessage']); //we need to remove messages, so they do not persist
   }

   function redirect($to = ''){ //you need to ensure you are not echoing any content before redirecting (that's a proper common way - learn it)
      $url = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
      header('Location: ' . $url .'/'. $to, true, 302);
      header('Connection: close');
      exit;
   }

   private function login($userId){ //actual answer to the question - how to store the logged user
      $_SESSION['logged'] = $userId;
   }

   private function flash($message){ //do not repeat yourself
      if(!isset($_SESSION['flashmessage']))
         $_SESSION['flashmessage'] = array();
      $_SESSION['flashmessage'][] = $message;
   }

   private function getFlashes(){
      return isset($_SESSION['flashmessage'])? $_SESSION['flashmessage']: [];
   }

   private function getPost($name, $default = null){ //do not repeat yourself
      return isset($_POST[$name])? $_POST[$name]: $default;
   }

   private function getPostEscaped($name, $default = null){ //do not repeat yourself
      return ($value = $this->getPost($name))?
         Connection::getConnection()->real_escape_string($value): $default;
   }
}

$ua = new UserAuthenticator();
$ua->checkLogin();
$ua->showFlashMessages();

you need to store passwords with

$ua = new UserAuthenticator();
$password = $ua->getPasswordHash($plainTextPassword); //store this to database

in homepage.php you can check logged status with

$ua = new UserAuthenticator();
if(!$ua->isLogged()){ $ua->redirect('index.php'); } //redirect to login page if not logged in

not tested anything of this, so typo is possible - sorry :)

Reloecc
  • 256
  • 2
  • 13
0

Lets say your login was succesfull. All you have to do is this:

Session_start(); $_SESSION['id']= $row['id']; (make sure you changed mysql_num_rows to fetch assoc aswell)

Then on your index page at the top you add an if statement that checks wether or not the session has been set. For that you first need to call another session_start()

Hope this steers you in the right direction if not ill update my answer

Waro1234
  • 73
  • 3