'Войти через Facebook'. Это правильный способ сделать FB Connect? 'Войти через Facebook' Безусловный account fb connect php

Абсолютно используйте SDK. Преимущество в том, что это библиотека, которая тестировалась и использовалась в дикой природе. Никогда не перестраивайте колесо, когда вам этого не нужно (вы обнаружите, что вы сделаете больше;)).

То, что я закончил в CI, заключалось в том, чтобы добавить PHP PHP SDK в каталог моих библиотек и изменить функцию __construct класса Facebook:

Public function __construct() { $ci =& get_instance(); $this->setAppId($ci->config->item("fb_appId")); $this->setApiSecret($ci->config->item("fb_secret")); $this->setCookieSupport($ci->config->item("fb_cookie")); $this->setBaseDomain($ci->config->item("fb_domain")); $this->setFileUploadSupport($ci->config->item("fb_upload")); }

Как только это было сделано, я смог получить доступ к FB API из любого места в своем приложении через $this->facebook .

Сказав все это, все это было до 2.0, поэтому я не совсем уверен, какие изменения будут в случае необходимости (я использую Yii сейчас, и именно поэтому я не знаю, нужны ли изменения:.))

Надеюсь, что это поможет.

Class UserModel extends Model { private $m_user; public function UserModel() { parent::Model(); $this->m_user = null; $session = $this->facebook->getSession(); if($session) { if($this->facebook->api("/me") != null) { $this->m_user = $this->facebook->api("/me"); } } } public function getUser() { return $this->m_user; } public function isLoggedIn() { return $this->getUser() != null; } // returns either the login or logout url for the given provider, relative to the // state that the current user object is in public function getActionUrl() { if($this->isLoggedIn()) { return $this->facebook->getLogouturl(); } else { return $this->facebook->getLoginUrl(array("next"=>currentUrl(), "cancel"=>currentUrl(), "req_perms"=>null, "display"=>"popup")); } } }

Logout

Второе редактирование:

Простите, прошло некоторое время с тех пор, как я это написал, поэтому мне пришлось вернуться и выяснить, как это реализовано: P После быстрого grep я обнаружил, что я вообще не использую getActionUrl . Я добавил несколько клиентов script для прослушивания событий входа/выхода в FB:

Google.setOnLoadCallback(on_load); google.load("jquery", "1.4.4"); window.fbAsyncInit = function() { FB.init({appId: "", status: true, cookie: true, xfbml: true}); FB.Event.subscribe("auth.login", on_fb_login); FB.Event.subscribe("auth.logout", on_fb_logout); }; function on_load() { // force all anchors with the rel tag "ext" to open in an external window // (replaces target= functionality) $("a").click(function(){ window.open(this.href); return false; }); } function on_fb_login() { location.reload(); } function on_fb_logout() { location.reload(); }

Абсолютно использовать SDK. Преимущество в том, что это библиотека, которая протестирована и используется в дикой природе. Никогда не перестраивайте колесо, когда вам этого не нужно (вы обнаружите, что вы сделаете больше);).

То, что я в конечном итоге делает в CI был добавить Facebook PHP SDK в мой каталог библиотеки и изменить __construct функцию Facebook класса быть:

Public function __construct() { $ci =& get_instance(); $this->setAppId($ci->config->item("fb_appId")); $this->setApiSecret($ci->config->item("fb_secret")); $this->setCookieSupport($ci->config->item("fb_cookie")); $this->setBaseDomain($ci->config->item("fb_domain")); $this->setFileUploadSupport($ci->config->item("fb_upload")); }

Как только это было сделано, я смог получить доступ к FB API из любого места в своем приложении через $this->facebook .

Сказав все это, все это было до 2.0, поэтому я не совсем уверен в том, какие изменения будут в случае необходимости (я использую Yii сейчас, и именно поэтому я не знаю, обязательный:)).

Надеюсь, что это поможет.

В соответствии с просьбой, я в конечном итоге добавив UserModel класс (расширение Model). У меня есть поддержка для нескольких пользователей, поэтому я не буду публиковать все это. Но это суть его:

Class UserModel extends Model { private $m_user; public function UserModel() { parent::Model(); $this->m_user = null; $session = $this->facebook->getSession(); if($session) { if($this->facebook->api("/me") != null) { $this->m_user = $this->facebook->api("/me"); } } } public function getUser() { return $this->m_user; } public function isLoggedIn() { return $this->getUser() != null; } // returns either the login or logout url for the given provider, relative to the // state that the current user object is in public function getActionUrl() { if($this->isLoggedIn()) { return $this->facebook->getLogouturl(); } else { return $this->facebook->getLoginUrl(array("next"=>currentUrl(), "cancel"=>currentUrl(), "req_perms"=>null, "display"=>"popup")); } } }

Logout

Второе редактирование:

К сожалению, это было в то время как я написал это, поэтому мне пришлось вернуться и выяснить, как это реализовано: P После быстрого grep я обнаружил, что я не использую getActionUrl в любом месте. Я добавил несколько сценариев для прослушивания событий входа/выхода в FB:

Google.setOnLoadCallback(on_load); google.load("jquery", "1.4.4"); window.fbAsyncInit = function() { FB.init({appId: "", status: true, cookie: true, xfbml: true}); FB.Event.subscribe("auth.login", on_fb_login); FB.Event.subscribe("auth.logout", on_fb_logout); }; function on_load() { // force all anchors with the rel tag "ext" to open in an external window // (replaces target= functionality) $("a").click(function(){ window.open(this.href); return false; }); } function on_fb_login() { location.reload(); } function on_fb_logout() { location.reload(); }

Nowadays the web users are not interested in filling a big form for registration on the website. Short registration process helps to get more subscribers to your website. Login with Facebook is a quick and powerful way to integrate registration and login system on the website. Facebook is a most popular social network and most of the users have a Facebook account. Facebook Login allows users to sign into your website using their Facebook account credentials without sign up on your website.

PHP SDK allows accessing the Facebook API from the web application. You can easily implement the Login with Facebook account using Facebook SDK for PHP. In this tutorial will show how you can implement user login and registration system with Facebook using PHP and store the user profile data into the MySQL database. Our example Facebook Login script uses Facebook PHP SDK v5 with Facebook Graph API to build Facebook Login system with PHP and MySQL.

To get started with the latest version of Facebook SDK v5.x , make sure your system meets the following requirements.

  • Navigate to the Settings » Basic page.
  • Navigate to the Facebook Login » Settings page.
    • In the Valid OAuth Redirect URIs field, enter the Redirect URL.
    • Click the Save Changes .
  • Go to the Settings » Basic page, note the App ID and App Secret . This App ID and App secret allow you to access the Facebook APIs.

    Note that: The App ID and App secret need to be specified in the script at the time of Facebook API call. Also, the Valid OAuth Redirect URIs must be matched with the Redirect URL that specified in the script.

    Get the Profile Link and Gender

    To retrieve the user’s Facebook timeline link and gender, you need to submit a request for user_link and user_gender permissions.


    Once the review process is completed and approved by the Facebook, you will be able to get the user profile link and gender from the Facebook Graph API.

    Do you want a detailed guide on Facebook App creation? Go through this guide to .

    Create Database Table

    To store the user’s profile information from Facebook, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database to hold the Facebook account information.

    CREATE TABLE `users` (`id` int (11 ) NOT NULL AUTO_INCREMENT, `oauth_provider` enum("" ,"facebook" ,"google" ,"twitter" ) COLLATE utf8_unicode_ci NOT NULL , `oauth_uid` varchar (50 ) COLLATE utf8_unicode_ci NOT NULL , `first_name` varchar (25 ) COLLATE utf8_unicode_ci NOT NULL , `last_name` varchar (25 ) COLLATE utf8_unicode_ci NOT NULL , `email` varchar (25 ) COLLATE utf8_unicode_ci NOT NULL , `gender` varchar (10 ) COLLATE utf8_unicode_ci DEFAULT NULL , `picture` varchar (200 ) COLLATE utf8_unicode_ci NOT NULL , `link` varchar (100 ) COLLATE utf8_unicode_ci NOT NULL , `created` datetime NOT NULL , `modified` datetime NOT NULL , PRIMARY KEY (`id` )) ENGINE =InnoDB DEFAULT CHARSET =utf8 COLLATE =utf8_unicode_ci; Facebook SDK for PHP

    The facebook-php-graph-sdk/ directory contains the latest version (v5) of Facebook SDK for PHP. You don’t need to download it separately, all the required files of Facebook PHP SDK v5 are included in our Facebook Login PHP source code.

    User Class (User.class.php)

    The User class handles the database related operations (connect, insert, and update) using PHP and MySQL. It helps to connect to the database and insert/update Facebook account data in the users table.

    • __construct() – Connect to the MySQL database.
    • checkUser() – Insert or update the user profile data based on the OAuth provider and ID. Returns the user’s account data as an array.