What is the implementation method in PHP to identify that the URL has been tampered with and block access?

In PHP, there are several ways to identify and block access to tampered URLs. Here are some common methods:

  1. Basic Authentication: Basic HTTP authentication can be implemented using PHP's $_SERVER['PHP_AUTH_USER']and variables. $_SERVER['PHP_AUTH_PW']Users can be asked to enter a username and password before accessing protected pages. If the credentials provided are invalid, access can be blocked.
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
    
    
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
}

// 检查凭据是否有效
if ($_SERVER['PHP_AUTH_USER'] != 'username' || $_SERVER['PHP_AUTH_PW'] != 'password') {
    
    
    echo 'Access Denied';
    exit;
}

// 允许访问受保护的页面
  1. Form validation: Add a hidden field to the form page that requires users to fill in the correct values ​​when submitting the form. On the server side, you can verify that the hidden field's value matches the expected value. If authentication fails, access can be blocked.
// 在表单中添加隐藏字段
<input type="hidden" name="security_token" value="your_security_token">

// 在服务器端验证表单提交
if (empty($_POST['security_token'])) {
    
    
    echo 'Invalid form submission';
    exit;
}

// 验证隐藏字段的值是否与预期值匹配
if ($_POST['security_token'] != 'your_security_token') {
    
    
    echo 'Security token mismatch';
    exit;
}

// 允许访问受保护的页面
  1. Use a token: Add a unique token to the URL and provide the correct token each time you access it. On the server side, the validity of the token can be verified. If the token is invalid, access can be blocked.
// 在 URL 中添加令牌
$token = generateToken(); // 生成唯一的令牌
$url = 'http://example.com/protected_page?token=' . $token;

// 在服务器端验证令牌
if (empty($_GET['token'])) {
    
    
    echo 'Invalid URL';
    exit;
}

$validToken = generateToken(); // 生成新的令牌进行验证
if ($_GET['token'] !== $validToken) {
    
    
    echo 'Invalid token';
    exit;
}

// 允许访问受保护的页面

These methods can help identify and block access to URLs that have been tampered with. Please note that these methods are not completely safe, but they can increase security and reduce potential risks. In practical applications, other security measures should be combined to ensure the security of the website.


@missingsometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/132634233
Recommended