I am trying to get the title of a few pages in PHP with this code. It works fine with almost every link except for a few, for example, with 9gag.
function download_page($url)
{
$agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
return $data;
}
function get_title_tag($str)
{
$pattern = '/<title[^>]*>(.*?)<\/title>/is';
if(preg_match_all($pattern, $str, $out))
{
return $out[1][0];
}
return false;
}
$url = "https://9gag.com/gag/avPBX3b";
$data = download_page($url);
echo $extracted_title = get_title_tag($data);
It echoes
Attention Required! | Cloudflare
which seems to be protected by a Cloudflare bot verification page. But when I try to post this link on any social network, they are able get the title and all the metadata required. How is it possible?
Edit:
Even if I use the opengraph.io API, I get:
"root":{
"error":{
"code": 2005
"message": "Got 403 error from server."
}
}