【问题标题】:How to get headers by curl like get_headers如何通过 curl 获取标题,如 get_headers
【发布时间】:2018-01-27 18:44:34
【问题描述】:


我知道这已经被问过很多次了,
但这一次应该是最后一次,因为解决方案应该是通用的
并且是独一无二的,任何人都可以在项目的任何地方使用代码。
所以问题是:如何使用 curl 以与生成数组的 get_headers 相同的方式获取任何网站标题。

【问题讨论】:

标签: php arrays curl get-headers


【解决方案1】:

我知道我正在回答我自己的问题,但因为我自己一直在编写代码。
我正在查看 stackoverflow 和其他网站上的一些答案,
所以我提供了简单的代码普遍而独特的结果。

我希望我不必解释如何使用代码,因为它是由简单的逻辑制成的。

<?php
function curl_get_headers($base_url){
    if(ini_get('allow_url_fopen')){
        $result_header = get_headers($base_url);
    }elseif(in_array('curl', get_loaded_extensions())){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $base_url);
        if(strpos($base_url,'https') !== false){
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        preg_match_all('/(.*)/',$response,$results);
        foreach($results AS $result_key=>$result_array){
            foreach($result_array AS $value){
                if(strlen($value)>=10){
                    $string = preg_replace('/\s+$/','',$value);
                    $result[$result_key][] = $string;
                }
            }
        }
        $result_header = end($result);
    }else{
        /* Because we got this far, tell the user what to do! */
        die('<h1 align="center">Server error : allow_url_fopen and curl is not enabled,<br />please ask your webhosting to enable one of the option!</h1>');
    }
    return $result_header;
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多