How to tell if Facebook app is on a page?

facebook, web-scraping

Solution

Unless Facebook changes their URL scheme, this works.

Note, that this method issues a `HEAD` request, rather than `GET`. Therefore, no content is downloaded. For further explanation how/why this works refer to http://anuary.com/47/keeping-facebook-portfolio-up-to-date.

Take a note that if Page privacy settings restrict unauthenticated users, you need to fake user authentication in order for this to work.

$fn_is_app_on_page  = function($page_id, $app_id)
{
    $ch         = curl_init();

    curl_setopt_array($ch,
    [
        CURLOPT_USERAGENT       => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11',
        CURLOPT_URL             => 'https://www.facebook.com/pages/anuary/' . $page_id . '?sk=app_' . $app_id,
        CURLOPT_FOLLOWLOCATION  => TRUE,
        CURLOPT_HEADER          => FALSE,
        CURLOPT_NOBODY          => TRUE
    ]);

    $response   = curl_exec($ch);

    $info       = curl_getinfo($ch);

    curl_close($ch);

    if($info['http_code'] == '404')
    {
        return FALSE;
    }

    if(strpos($info['url'], (string) $app_id) !== FALSE)
    {
        return TRUE;
    }

    return FALSE;
};

$fn_is_app_on_page(130414917005937, 299770086775725); // TRUE
$fn_is_app_on_page(1, 299770086775725); // FALSE
$fn_is_app_on_page(130414917005937, 1); // FALSE

Problem

The approach I've been using initially was: ``` http_head('http://www.facebook.com/pages/Test/' . $input['fb_page_id'] . '?sk=app_' . $input['fb_id']), 'HTTP/1.1 301 Moved Permanently') ``` The problem with this approach is: - If the page doesn't exist at all, Facebook will return `200` header, rather than `404` (eg. `http://www.facebook.com/pages/Test/DominosPizza?sk=app_311706258843058`). - If page has a username, this request will return response `301` response. I am building a script that occasionally goes through all instances of `<div data-page="130414917005937" data-app="299770086775725"></div>` in my portfolio. Then checks if the app is still on the page. If the app is on the page, it will provide a link, otherwise leave the tag as it was. I am looking for a solution that does not require access token.

Original source