PHP:检查 URL 是否重定向?

标签 php function redirect curl

我已经实现了一个功能,该功能在我想限制未登录用户访问的每个页面上运行。如果访问者未登录,该功能会自动将访问者重定向到登录页面。

我想制作一个从外部服务器运行的 PHP 函数,并循环访问多个设置的 URL(包含每个 protected 站点的 URL 的数组)以查看它们是否被重定向。因此,我可以轻松地确定保护是否已启动并在每个页面上运行。

这是怎么做到的?

谢谢。

最佳答案

$urls = array(
    'http://www.apple.com/imac',
    'http://www.google.com/'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

foreach($urls as $url) {
    curl_setopt($ch, CURLOPT_URL, $url);
    $out = curl_exec($ch);

    // line endings is the wonkiest piece of this whole thing
    $out = str_replace("\r", "", $out);

    // only look at the headers
    $headers_end = strpos($out, "\n\n");
    if( $headers_end !== false ) { 
        $out = substr($out, 0, $headers_end);
    }   

    $headers = explode("\n", $out);
    foreach($headers as $header) {
        if( substr($header, 0, 10) == "Location: " ) { 
            $target = substr($header, 10);

            echo "[$url] redirects to [$target]<br>";
            continue 2;
        }   
    }   

    echo "[$url] does not redirect<br>";
}

关于PHP:检查 URL 是否重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2964834/

相关文章:

PHP 分页 - 仅 1 页有效

php - 如何从网页函数中调用php类中的函数

sql - 如何确定 Crystal Reports 函数的用途?

model-view-controller - 可以在 RESTful MVC 框架中使用 HTTP 重定向吗?

php - 从 Javascript Canvas 图像信息和一些变量传递到 PHP

php - Centos 7/Apache/PHP - mkdir() : Permission denied

c# - 枚举函数错误

bash - 在 AIX 中将 STDERR 和 STDOUT 重定向到/dev/null 失败

.htaccess - 如何将所有网站请求重定向到没有 www 的 HTTPS

php - 使用 php 从 mySQL 数据库创建 xml 时出错