首页 > 解决方案 > PHP get_headers 有时将位置返回为数组

问题描述

我不明白为什么,有时

$headers = @get_headers($url , true);

Location字段作为数组而不是字符串返回......

所以如果我需要获取完整的网址,当它是一个字符串时,我会做

$unshorted_url = $headers['Location'];

但是当Location作为数组返回时,我不知道我需要考虑什么索引......

有什么建议吗?更重要的是.....为什么Location有时会以数组的形式返回?

当我尝试获取这样的 ebay 网址时,我看到了这个“问题”https://ebay.us/JOBBf0

标签: php

解决方案


如果 URL 被重定向并且新目标也被重定向,我们会在数组中获取 Locations,并且还会在数字索引值中获取 HTTP 代码。

让我们想象一下这个重定向链:

/index.php?id=1-> /index.php?id=2->/index.php?id=3

位置将是:

[Location] => Array
    (
        [0] => /index.php?id=2
        [1] => /index.php?id=3
    )

id=3将是登录页面。

如果您想要第一个重定向(id=2在示例中):

$headers = get_headers($url, true);

if (is_array($headers['Location'])) {
    $unshorted_url = reset($headers['Location']);
} else {
    $unshorted_url = $headers['Location'];
}

如果您想要登陆页面,您可以使用end()reset()不是。


推荐阅读