如果用户使用php登录,如何仅使页面可访问

时间:2019-03-07 11:00:00

标签: php html login

我正在一个有登录表格的网站上工作。用户可以输入信息,如果输入错误,站点将发送警报。但是,问题在于,您可以在登录后通过更改地址栏中的名称轻松地转到该页面。

这很糟糕,因为您无需登录即可轻松进入页面。

validation.php:

<?php

$name =$_POST['user'];
$pass =$_POST['password'];
//Test code
//echo $pass; 
//End Test Code

//Connection Code
session_start();
$con = mysqli_connect('localhost', 'root', '');
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 
mysqli_select_db($con, 'userregistration');
// Connection End

//Query Code

$s = "select * from usertable where name = '$name' and password = '$pass'";
//test
//echo $s;
$result = mysqli_query($con, $s);

$num = mysqli_num_rows($result);

if($num == 1){

    echo "Hello " . $name;

}
else{

   echo "<script>";
   echo "alert('Incorrect Username or Password');";
   echo "window.location.replace('login.html');";
   echo "</script>";

}

?>
<!--html code-->

Donate.php

<center><h1>Donate Here!</h1></center>

3 个答案:

答案 0 :(得分:1)

您必须在成功登录后创建会话:

session_start();

if ($num == 1) {
    $_SESSION['username'] = $name;
}

现在,在Donate.php中,通过检查是否设置了会话来检查用户是否登录:

session_start();

if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
    // no session, redirect user to index.php
    header('location: index.php');
}

答案 1 :(得分:0)

如果您想限制Donate.php,请尝试

npx aws-api-gateway-cli-test --username='mail@example.com' --password='password' --user-pool-id='user-pool-id' --app-client-id='app-client-id' --cognito-region='region' --identity-pool-id='identity-pool' --invoke-url='url' --api-gateway-region='region' --path-template='/notes' --method='POST' --body='{"content":"hello world","attachment":"hello.jpg"}'
npx: installed 106 in 7.229s
Authenticating with User Pool
Given user needs to set a new password

答案 2 :(得分:0)

您必须在会话中设置某种标记,以标记用户已通过身份验证(登录)的事实。您可以将当前用户的user_id存储在$_SESSION['current_user_id']中。

还请注意,您的查询是sql注入的良好目标,因此请不要忘记让通过mysqli_real_escape_string添加到sql查询的任何数据转出SQL

validation.php:

//...
$s = "select * from usertable where name = '"
     .mysqli_real_escape_string($con, $name).
     "' and password = '"
     .mysqli_real_escape_string($con, $pass)
     ."'";

$result = mysqli_query($con, $s);

if ($row = mysqli_fetch_row($result))
{
  // row fecthed, user found
  $user_id = $row['user_id']; // Let expect that usertable has user_id column
  $_SESSION['current_user_id'] = $user_id;
}
else
{
   echo "<script>";
   echo "alert('Incorrect Username or Password');";
   echo "window.location.replace('login.html');";
   echo "</script>";
   exit();
}
//...

在您所有的页面上,首先输入代码:

some_page.php:

if (!isset($_SESSION['current_user_id'])) { exit('Your session expiried!') }
//... do some stuff

要注销用户,您只需取消设置$_SESSION['current_user_id']

logout.php:

unset($_SESSION['current_user_id']);