SwegreDesigns
SwegreDesigns

Reputation: 189

Page accessible only if logged in

Hello Stackoverflowers

Im new to PHP and im trying to make a members area for my testpage. I have made a successful register and login page, but now when I changed the code so if I log in correctly it redirects my to a page, and if I log in with wrong information it send me to a different page. However the members area is accessible if you type the location in the address-bar. Now, here's what I need help with, When someone tries to access that location without being logged in it should say "Access denied" but when you log in, it should redirect you to the members area and all it content is shown.

Here is my code:

login.php

<?php
session_start();
  $host = 'localhost';
  $user = 'root';
  $pass = '';
  $db = 'Data';

mysql_connect($host, $user, $pass);
mysql_select_db($db);

 if(isset($_POST['username'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $sql = "SELECT * FROM Project WHERE username='$username' AND password='$password' LIMIT 1";
    $res = mysql_query($sql);
    if (mysql_num_rows($res) == 1){
      header("Location: loggedin.php");
      exit();
    } else {
      echo 'Anv&auml;ndarnamn eller l&ouml;senord st&auml;mmer ej med informationen i databasen, var sn&auml;ll f&ouml;rs&ouml;k igen <br>';
      echo '<a href="login.php">G&aring; tillbaka</a> Eller <a href="signup.php">Registrera dig</a>';

      exit();
    }
  }
?>


<html>

<head>

  <meta charset="UTF-8">

  <title>Logga in</title>

    <script src="js/prefixfree.min.js"></script>

</head>

<body>

  <div class="body"></div>
        <div class="grad"></div>
    <div class="wrapper">
        <div class="header">
            <div>bababa<span>bababa</span></div>
        </div>
        <br>
        <div class="login">
      <form method="post" action="login.php">
                <input type="text" placeholder="Anv&auml;ndarnamn" name="username" required><br>
                <input type="password" placeholder="L&ouml;senord" name="password" required><br>
                <input type="submit" value="Logga in">
      </form>
        </div>
  </div>

  <script src='http://codepen.io/assets/libs/fullpage/jquery.js'></script>

</body>

</html>

signup.php

<!DOCTYPE HTML>
<html lang="sv">
<head>
<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" >
$(".name").focus(function(){
  $(".name-help").slideDown(500);
}).blur(function(){
  $(".name-help").slideUp(500);
});

$(".email").focus(function(){
  $(".email-help").slideDown(500);
}).blur(function(){
  $(".email-help").slideUp(500);
});



</script>

</head>
<div class="wrapper">
  <h1>Registrera er h&auml;r</h1>
  <p>Detta &auml;r ett test-formul&auml;r f&ouml;r Webbutvecklingsprojektet. Skriv ditt namn h&auml;r
  under och om allt funkar r&auml;tt skall systemet lagra ditt namn i en MySQL databas.</p>

  <form class="form" name="form" method="post" action="add.php">

     <input type="text" id="username" name="username" placeholder="Anv&auml;ndarnamn" required>

     <input type="password" id="password" name="password" placeholder="L&ouml;senord" required>

 <input type="email" id="email" name="email" placeholder="E-mail" required>


    <input type="submit" class="submit" value="Registrera dig">

  </form>

  <h3>
    Allm&auml;nt & regler:
  </h3>
  <ul>
    <li>Maximalt 2GB Lagring</li>
    <li>Du m&aring;ste skriva f&ouml;r- och efternamn</li>
    <li>Databasen lagrar bara upp till 60 anv&auml;ndare</li>
  </ul>
</div>
<p class="optimize">
</p>
</html>

And last: loggedin.php

 <?php
session_start();
  $host = 'localhost';
  $user = 'root';
  $pass = '';
  $db = 'Data';

mysql_connect($host, $user, $pass);
mysql_select_db($db);

   if(!isset($_SESSION['username'])) {
   die("Please login");
} else {
echo 'Du &auml;r inloggad';
}
?>

FTR: I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?

Im a newbie at this so help me a bit extra

Thank you!

Upvotes: 0

Views: 5439

Answers (4)

Moid
Moid

Reputation: 1447

You can use Cookies or SESSION to do this.

When a user is authenticated, before redirecting to homeS page you should set a session variable like this: $_SESSION['id']=$user_id;. And if you want to set COOKIES so that user can access his account directly even after closing browser, you can set it like this setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // for 1 day.

So, now at the start of every page you need to start session session_start() to get the session value you set during login. If a user_id of any user info exists in the session it will automatically use that info to access the page.

Now considering you want that the user is automatically redirected to login page/ACCESS DENIED if he tries to access home page.. You can do this by checking if the session user_info or cookie exist or not...if it doesn't redirect him to the login page or any error page as per you need...

In your code, before header("Location: loggedin.php"); create a session $_SESSION['username'] = $username;. And keep in mind to session_start() on every page, where $_SESSION value is going to be used..

Upvotes: 1

Andr&#233; Ferraz
Andr&#233; Ferraz

Reputation: 1521

You have started the session session_start, but you haven't actually set the $_SESSION['username']. You need to set the session variable in between these two line.

if (mysql_num_rows($res) == 1){
  // set session variable here
  header("Location: loggedin.php");
  exit();
}

Make sure you use the session_start() on the top of every page so that your able to check if the person who is viewing the page is logged in.

Also just another tip mysql_connect has been deprecated see here, you can use mysqli or PDO which escapes things automatically for you.

Upvotes: 0

cooper
cooper

Reputation: 674

I tried the if isset but even when I logged in correctly the same message shows up: Please log in, how should I fix this?

OK, when you log in succesfully, just before you redirect the user to the other page:

header("Location: loggedin.php");

you've to assign a session variable to the user, like this (for example. It depends how you want to identify them).

$_SESSION['ID'] = $row['ID'];

I think this is enought

By the way, please, don't use mysql_query Use instead: mysqli extension. (for more information)

Hope it helps

Upvotes: 0

Christian Hagdorn
Christian Hagdorn

Reputation: 463

What you would do is to redirect to a login page if user is not logged in.

if(!isset($_SESSION['username'])){
    header('location: login.php');
}

Upvotes: 0

Related Questions