cURL,获取指向变量的重定向URL

7hiiyaii  于 2023-11-19  发布在  其他
关注(0)|答案(5)|浏览(171)

我使用curl来填充表单。完成后,处理表单的其他脚本将重定向到另一个URL。我想将此重定向URL放入变量中。

lg40wkob

lg40wkob1#

找到重定向URL的简单方法(如果你不想提前知道)

  1. $last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

字符串

uyto3xhc

uyto3xhc2#

你会用

  1. curl_setopt($CURL, CURLOPT_HEADER, TRUE);

字符串
并解析location头的头。

j91ykkif

j91ykkif3#

在这里我得到了资源http头,然后我将头解析到数组$retVal中。我从这里得到了解析头的代码(http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/)如果你有(PECL pecl_http >= 0.10.0),你也可以使用http://php.net/manual/en/function.http-parse-headers.php

  1. $ch = curl_init();
  2. $timeout = 0;
  3. curl_setopt ($ch, CURLOPT_URL, $url);
  4. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  5. curl_setopt($ch, CURLOPT_HEADER, TRUE);
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  7. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  8. // Getting binary data
  9. $header = curl_exec($ch);
  10. $retVal = array();
  11. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
  12. foreach( $fields as $field ) {
  13. if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
  14. $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
  15. if( isset($retVal[$match[1]]) ) {
  16. $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
  17. } else {
  18. $retVal[$match[1]] = trim($match[2]);
  19. }
  20. }
  21. }
  22. //here is the header info parsed out
  23. echo '<pre>';
  24. print_r($retVal);
  25. echo '</pre>';
  26. //here is the redirect
  27. if (isset($retVal['Location'])){
  28. echo $retVal['Location'];
  29. } else {
  30. //keep in mind that if it is a direct link to the image the location header will be missing
  31. echo $_GET[$urlKey];
  32. }
  33. curl_close($ch);

字符串

展开查看全部
nmpmafwu

nmpmafwu4#

您可能希望将CURLOPT_FOLLOWLOCATION设置为true。
或者将CURLOPT_HEADER设置为true,然后使用regexp获取Location头。

l2osamch

l2osamch5#

嗨。有一个新的简单方法。

如果CURLOPT_FOLLOWLOCATION选项被禁用(您不会被自动重定向)

您可以使用CURLINFO_REDIRECT_URL重定向上次交易中找到的URL

  1. $redirect_url = curl_getinfo($ch, CURLINFO_REDIRECT_URL);

字符串

或者如果启用了CURLOPT_FOLLOWLOCATION选项(自动重定向)

您可以使用CURLINFO_EFFECTIVE_URL:最后请求的URL(在这种情况下是最后重定向URL)

  1. $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

展开查看全部

相关问题