Search code examples
phpgoogle-custom-search

get_file_content not working for https


I am using php and google's new CSE in my website . The URL for request is like https://www.googleapis.com/customsearch/v1?key=INSERT-YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=lectures

The connection is https and file_get_content() is getting failed. How can i get it working?
Since i need to host the site on some external web-hosting servers, I am in need of solution which don't alter php configuration file or work with default options found on most of web-hosting sites.


Solution

  • You can use curl:

    ## HTTPS url that you are targeting.
    $url = "https://www.googleapis.com/customsearch/v1?key=INSERT-YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=lectures";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Opera/9.23 (Windows NT 5.1; U; en)');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    
    ## Below two option will enable the HTTPS option.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
    $result = curl_exec($ch);
    echo $result;