-2


i know this has been asked many many times before,
but this time should be the last time because the solution should be universal
and unique that anyone can use the code anywhere in the project.
So the question : How to get any website header using curl in the same way as get_headers which produce an array.

1 Answers1

0

I know i am answering my own question but because i have been working on the code myself.
I was looking at some answers on stackoverflow and other websites,
so i'm coming with simple code which give the universal and unique result.

I hope i don't have to explane it how to use the code because it's made by simple logic.

<?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;
}
?>