Facebook API: get random friend with PHP-Collection of common programming errors

I am trying to obtain a random friend. I found this thread on SO and it looks it should work. Here is my code:

            $config = array(
                'appId'  => APP_ID,
                'secret' => SECRET,
                'cookie' => true,
            );
            $facebook = new Facebook($config);

            $params = array(
                'method' => 'fql.query',
                'query' => "SELECT uid, name, sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) order by rand() limit 1",
            );

            $result = $facebook->api($params);
            echo print_r($result);

But I am getting the error:

Fatal error: Uncaught Exception: 102: Requires user session thrown in /home/path/to/base_facebook.php on line 1050

Where is the problem? I’ve tried to search possible problem, but I wasn’t much successful…

  1. Yes, as Jason commented, looks like you’ve not got an authenticated user.

    Since you’re using the PHP SDK, the quickest way to fix this is as follows

    $config = array(
        'appId'  => APP_ID,
        'secret' => SECRET,
        'cookie' => true,
    );
    $facebook = new Facebook($config);
    
    //This will redirect the user to a login/authentication dialog.
    if (!$facebook->getUser()) {
        echo "window.location = ' . $facebook->getLoginUrl() .'";
        exit();
    }
    
    $params = array().. etc, the rest of your code
    

    Lack of best practice code notwithstanding – That should do the trick

Originally posted 2013-11-19 13:17:00.