gpt4 book ai didi

php - 如何防止PHP发送的HTTP请求出现403错误?

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:12:47 27 4
gpt4 key购买 nike

我正在使用以下脚本将数据发布到外部站点。在下面的示例中,$method、$url 和 $postdata 已由用户收集。

foreach($postdata as $key => $value) 
{
$data .= $key . '=' . $value . '&';
}

if ($method == 'POST') {

// Set headers
$headers = array('http' => array(
'method' => $method,
'header' => "accept-language: en\r\n" .
"Host: $host\r\n" .
"Referer: $url\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $data));

// Send request and retreive response
$context = stream_context_create($headers);
$fp = fopen($url, 'rb', false, $context);
fpassthru($fp);
fclose($fp);

} else if ($method == 'GET') {

// Set headers
$headers = array('http' => array(
'method' => $method,
'header' => "accept-language: en\r\n" .
"Host: $host\r\n" .
"Referer: $url\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n"));

// Append url
$url .= '?' . $data;

// Send request and retreive response
$context = stream_context_create($headers);
$fp = fopen($url, 'rb', false, $context);
fpassthru($fp);
fclose($fp);

} else {
echo 'Invalid method.';
}

它在大多数情况下工作正常,但是有些站点会发回 403 Forbidden,表面上是因为它们不喜欢 fopen() 请求。有没有解决的办法?如果我改用 cURL,它会阻止 403 吗?而且,如果是这样,执行上述操作的 curl 方式是什么?谢谢。

最佳答案

您可能希望确保将 USER-AGENT 与 header 一起传递。我从事的项目需要我们登录到远程系统,以便我们可以提取数据,但在其中一些系统上,如果我们没有通过有效的用户代理,我们将无法获得访问权限,即使登录凭据是正确设置。

关于php - 如何防止PHP发送的HTTP请求出现403错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9558828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com