-2


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

4

1 回答 1

0

我知道我正在回答我自己的问题,但因为我自己一直在编写代码。
我正在查看 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;
}
?>
于 2018-01-27T18:59:04.423 回答