如何阻止自动请求

How to block automated requests

我想阻止'get_file_contents', 自动 'curl' 请求 以及对抓取数据的自动请求 在我的项目中。

我不想使用 WAF 或外部系统执行此操作。

如何仅使用 PHP 解析传入请求?

您可以使用 recaptcha 编写自己的机器人检查。只需在没有适当会话的情况下向用户展示机器人检查,并只允许通过测试的访问者访问内容。

例如,

<?php

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
    // Build POST request:
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_secret = 'YOUR_RECAPTCHA_SECRET_KEY';
    $recaptcha_response = $_POST['recaptcha_response'];

    // Make and decode POST request:
    $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
    $recaptcha = json_decode($recaptcha);

    // Take action based on the score returned:
    $_SESSION['human'] = ($recaptcha->score >= 0.8);
}

if (!isset($_SESSION['human']) || !$_SESSION['human']) {

    echo <<<HTML
<html>
<head>
<title>Human Test</title>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
  document.getElementById("demo-form").submit();
}
</script>
</head>
<body>
<form method="POST" id="demo-form">
  <button class="g-recaptcha"
    data-sitekey="reCAPTCHA_site_key" 
    data-callback='onSubmit' 
    data-action='submit'>I am a Human :-)</button>
</form>
</body>
</html>
HTML;
    exit;
}


// Whatever content you want to show originally
// ...
// ...

这会阻止大多数抓取工具。