【发布时间】:2026-02-01 20:15:02
【问题描述】:
我有一个将 POST 数据发送到多个页面的脚本。但是,我在向某些服务器发送请求时遇到了一些困难。原因是重定向。这是模型:
- 我正在向服务器发送 post 请求
- 服务器响应:301 已永久移动
- 然后 curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE) 启动并遵循重定向(但通过 GET 请求)。
为了解决这个问题,我正在使用 curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST") 是的,现在它的重定向没有我在第一个请求中发送的 POST 正文内容。如何在重定向时强制 curl 发送帖子正文?谢谢!
示例如下:
<?php
function curlPost($url, $postData = "")
{
$ch = curl_init () or exit ( "curl error: Can't init curl" );
$url = trim ( $url );
curl_setopt ( $ch, CURLOPT_URL, $url );
//curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postData );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
curl_setopt ( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36");
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE);
$response = curl_exec ( $ch );
if (! $response) {
echo "Curl errno: " . curl_errno ( $ch ) . " (" . $url . " postdata = $postData )\n";
echo "Curl error: " . curl_error ( $ch ) . " (" . $url . " postdata = $postData )\n";
$info = curl_getinfo($ch);
echo "HTTP code: ".$info["http_code"]."\n";
// exit();
}
curl_close ( $ch );
// echo $response;
return $response;
}
?>
【问题讨论】:
-
用例子把你的php代码放在post中