Saturday, January 15, 2022

[FIXED] Facebook not able to scrape my url if session is set in codeigniter

Issue

I am using addthis for sharing and framework is Code Igniter.

Problem is if in my controller i check session then facebook not able to scrape my url.If i remove session then it is working. So what can i do to working fb sharing with session.

The following code is working:
controller

public function index()
{
     $this->load->view('client/home');
}

if i check session then fb sharing is not working:

public function index()
{
    if(!$this->session->userdata('client_id'))
    {
        redirect('client/login/index', 'refresh');
        exit;
    }
     $this->load->view('client/home');
}

Thanks in advance.

sidenote: i set session when customer login into website. so when customer click on FB sharing button the session is already set.


Solution

Try this modified version of the code:

public function index()
{
    if(!$this->session->userdata('client_id') && !strstr( $_SERVER['HTTP_USER_AGENT'], 'facebookexternalhit') )
    {
        redirect('client/login/index', 'refresh');
        exit;
    }
     $this->load->view('client/home');
}

I've added an condition, which checks to see if the user agent is the Facebook scraper (facebookexternalhit). If the user-agent is not Faecebook, it forces login. (Remember that user-agent can be spoofed). If it detect Facebook, it will load the page and allow Facebook to scrape the content correctly.



Answered By - Niraj Shah

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.