用数据重定向卷曲请求


Redirect Curl request with data

我有一个PHP curl请求,它可以工作-但是,如果我将CURLOPT_FOLLOWLOCATION设置为1,curl帖子将与postdata一起提交,重定向的页面HTML将被捕获并发布在我的本地服务器上。

整个重定向包含在我的本地服务器中,它实际上不会将我与数据一起转移到重定向本身(这正是我想要的)。在我的post.php上下载html几秒钟后,它重定向到一个找不到的页面。

但是,如果我将CURLOPT_FOLLOWLOCATION设置为0,然后获取正确的URL,然后通过header("Location: $redirect");重定向它,它可以传输,但不会传输更多的数据。

将数据传输到新标头位置的最佳方式是什么。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'postdata=' . urlencode(xmlGrab()));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
// Download the given URL, and return output
$output = curl_exec($ch);
$headers = substr($output, 0, $curl_info["header_size"]); //split out header
$redirect = curl_getinfo($ch)['redirect_url'];
header('HTTP/1.1 307 Temporary Redirect');
header("Location: $redirect");
// Close the cURL resource, and free system resources
curl_close($ch);

示例场景:

  • 用户提交帖子http://localhost:8888/post.php
  • Post.php包含到google.co.uk的连接
  • Post.php连接并在google.co.uk上发帖
  • 请求下载google.co.uk?q=到post.php的废话
  • post.php看起来和谷歌网站一模一样?q=诸如此类
  • 3秒钟后,它重定向到http//localhost:8888/?q=诸如此类

检查$redirect的值。

如果它是一个相对的url,你必须在url前面加上协议+主机名+etc,否则你最终会在本地服务器上。