只允许从另一个.php文件访问.php文件,而不允许直接访问url


allow access to a .php file only from another .php file and not direct url

我在本地服务器的一个文件夹中存储了两个文件,login.php和update.php。这两个文件可以从任何位置访问,只要它们输入:

ip:port/folder/login.php

ip:port/folder/update.php.

我试图做的是通过在url中输入update.php来阻止用户访问update.php,并且只允许他们通过首先访问login.phpupdate.php文件(按下按钮时,login.php会将他们重定向到update.php)。

我对php和apache有点陌生。我不确定这是否应该在PHP或.htaccess文件中完成,以及如何完成。

提前感谢!

您可以使用$_SESSION

// Let's say this is you update.php
session_start();
if (isset($_SESSION['email']) /* or something like that */)
{                     
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}
// do whateven you need to do and set up $_SESSION variables 
// for example get the user entered info here
// This is how you set session variables
$_SESSION['username'] = ...;
$_SESSION['email']    = ...;
// Then after you did the registration part or something else you wanted to do
// You can redirect the user to any page you want
header("Location: some_other_page.php");

每次用户尝试立即输入update.php时,他或她都会在注销后重定向到登录,因为会话不在那里。

希望这能有所帮助

不可能有一个用户只能访问的URL。

如果你想要一个登录系统,那么做其他人都做的事:

  1. 登录时设置识别cookie
  2. 当用户访问受限页面时:
    1. 测试您是否已识别他们
    2. 测试已识别的用户是否有权查看页面
    3. 将他们重定向到登录页面,或者如果前两个条件中的任何一个都失败,则向他们发出未经授权的响应

您可以让它检查推荐url。您还可以创建一个用户会话,以便在用户访问更新时使用。php中,验证了一个变量。登录时可以将会话变量设置为正确的值。Php。

会话允许您在人们在您的网站上从一页转到另一页时存储变量。

一个很好的方法是使用readfile。

<?php
// This is the path to your PDF files. This shouldn't be accessable from your
// webserver - if it is, people can download them without logging in
$path_to_pdf_files = "/path/to/pdf/files";
session_start();
// Check they are logged in. If they aren't, stop right there.
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] != true) {
    die("You are not logged in!");
}
// Get the PDF they have requested. This will only allow files ending in 'pdf'
// to be downloaded.
$pdf_file = basename($_GET['file'], ".pdf") . ".pdf";
$pdf_location = "$path_to_pdf_files/$pdf_file";
// Check the file exists. If it doesn't, exit.
if (!file_exists($pdf_location)) {
    die("The file you requested could not be found.");
}
// Set headers so the browser believes it's downloading a PDF file
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=$pdf_file");
$filesize = filesize($pdf_location);
header("Content-Length: $filesize");
// Read the file and output it to the browser
readfile($pdf_location);
?>

这是取自wildeo-ga在谷歌答案上的回答。