简体   繁体   English

页面只有登录才能访问

[英]Page accessible only if logged in

Hello Stackoverflowers 你好Stackoverflowers

Im new to PHP and im trying to make a members area for my testpage. 我对PHP还是陌生的,我试图为我的测试页添加一个成员区域。 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 的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 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 最后:loginin.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? FTR:我尝试过if isset,但是即使我正确登录也出现相同的消息:请登录,我该如何解决?

Im a newbie at this so help me a bit extra 我是新手,请多帮我一下

Thank you! 谢谢!

You can use Cookies or SESSION to do this. 您可以使用CookiesSESSION来执行此操作。

When a user is authenticated, before redirecting to homeS page you should set a session variable like this: $_SESSION['id']=$user_id; 通过用户身份验证后,在重定向到homeS页面之前,您应该设置一个会话变量,如下所示: $_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 并且,如果要设置COOKIES以便即使关闭浏览器后用户也可以直接访问其帐户,则可以将其设置为以下setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // for 1 day setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // for 1 day . 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. 因此,现在在每个页面的开头,您需要启动会话session_start()来获取您在登录期间设置的session值。 If a user_id of any user info exists in the session it will automatically use that info to access the page. 如果会话中存在任何用户信息的user_id ,它将自动使用该信息来访问页面。

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... 现在考虑您要让用户尝试访问主页时自​​动将其重定向到登录页面/拒绝访问。您可以通过检查会话user_info或cookie是否存在来实现此目的...如果它不重定向他到登录页面或根据需要的任何错误页面...

In your code, before header("Location: loggedin.php"); 在您的代码中,在header("Location: loggedin.php"); create a session $_SESSION['username'] = $username; 创建一个会话$_SESSION['username'] = $username; . And keep in mind to session_start() on every page, where $_SESSION value is going to be used.. 并记住每个页面上的session_start() ,其中将使用$_SESSION值。

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');
}

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? 我尝试了if isset,但是即使我正确登录也出现了相同的消息:请登录,我该如何解决?

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. 顺便说一句,请不要使用mysql_query代替:mysqli扩展。 (for more information ) (更多信息

Hope it helps 希望能帮助到你

You have started the session session_start , but you haven't actually set the $_SESSION['username'] . 您已经启动了会话session_start ,但实际上尚未设置$_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. 确保使用每个页面顶部的session_start() ,以便您能够查看正在查看该页面的人是否已登录。

Also just another tip mysql_connect has been deprecated see here , you can use mysqli or PDO which escapes things automatically for you. 同样,不推荐使用另一个技巧mysql_connect 请参见此处 ,您可以使用mysqliPDO来自动为您转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM