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

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.
    /* * User Class * This class is used for database related (connect, insert, and update) operations * @author сайт * @url http://www.сайт * @license http://www.сайт/license */ class User { private $dbHost = DB_HOST ; private $dbUsername = DB_USERNAME ; private $dbPassword = DB_PASSWORD ; private $dbName = DB_NAME ; private $userTbl = DB_USER_TBL ; function __construct (){ if(!isset($this -> db )){ // Connect to the database $conn = new mysqli ($this -> dbHost , $this -> dbUsername , $this -> dbPassword , $this -> dbName ); if($conn -> connect_error ){ die("Failed to connect with MySQL: " . $conn -> connect_error ); }else{ $this -> db = $conn ; } } } function checkUser ($userData = array()){ if(!empty($userData )){ // Check whether user data already exists in database $prevQuery = "SELECT * FROM " . $this -> userTbl . " WHERE oauth_provider = "" . $userData [ "oauth_provider" ]. "" AND oauth_uid = "" . $userData [ "oauth_uid" ]. """ ; $prevResult = $this -> db -> query ($prevQuery ); if($prevResult -> num_rows > 0 ){ // Update user data if already exists $query = "UPDATE " . $this -> userTbl . " SET first_name = "" . $userData [ "first_name" ]. "", last_name = "" . $userData [ "last_name" ]. "", email = "" . $userData [ "email" ]. "", gender = "" . $userData [ "gender" ]. "", picture = "" . $userData [ "picture" ]. "", link = "" . $userData [ "link" ]. "", modified = NOW() WHERE oauth_provider = "" . $userData [ "oauth_provider" ]. "" AND oauth_uid = "" . $userData [ "oauth_uid" ]. """ ; $update = $this -> db -> query ($query ); }else{ // Insert user data $query = "INSERT INTO " . $this -> userTbl . " SET oauth_provider = "" . $userData [ "oauth_provider" ]. "", oauth_uid = "" . $userData [ "oauth_uid" ]. "", first_name = "" . $userData [ "first_name" ]. "", last_name = "" . $userData [ "last_name" ]. "", email = "" . $userData [ "email" ]. "", gender = "" . $userData [ "gender" ]. "", picture = "" . $userData [ "picture" ]. "", link = "" . $userData [ "link" ]. "", created = NOW(), modified = NOW()" ; $insert = $this -> db -> query ($query ); } // Get user data from the database $result = $this -> db -> query ($prevQuery ); $userData = $result -> fetch_assoc (); } // Return user data return $userData ; } }

    Site Settings and API Configuration (config.php)

    The database settings and Facebook API configuration constant variables are defined in the config.php file.
    Database Constants:

    Call Facebook API:

    /* * Basic Site Settings and API Configuration */ // Database configuration define ("DB_HOST" , "MySQL_Database_Host" ); define ("DB_USERNAME" , "MySQL_Database_Username" ); define ("DB_PASSWORD" , "MySQL_Database_Password" ); define ("DB_NAME" , "MySQL_Database_Name" ); define ("DB_USER_TBL" , "users" ); // Facebook API configuration define ("FB_APP_ID" , "Insert_Facebook_App_ID" ); define ("FB_APP_SECRET" , "Insert_Facebook_App_Secret" ); define ("FB_REDIRECT_URL" , "Callback_URL" ); // Start session if(! session_id ()){ session_start (); } // Include the autoloader provided in the SDK require_once __DIR__ . "/facebook-php-graph-sdk/autoload.php" ; // Include required libraries use Facebook \ Facebook ; use Facebook \ Exceptions \ FacebookResponseException ; use Facebook \ Exceptions \ FacebookSDKException ; // Call Facebook API $fb = new Facebook (array("app_id" => FB_APP_ID , "app_secret" => FB_APP_SECRET , "default_graph_version" => "v3.2" ,)); // Get redirect login helper $helper = $fb -> getRedirectLoginHelper (); // Try to get access token try { if(isset($_SESSION [ "facebook_access_token" ])){ $accessToken = $_SESSION [ "facebook_access_token" ]; }else{ $accessToken = $helper -> getAccessToken (); } } catch(FacebookResponseException $e ) { echo "Graph returned an error: " . $e -> getMessage (); exit; } catch(FacebookSDKException $e ) { echo . $e -> getMessage (); exit; }

    Note that: You’ll find the App ID and App Secret on your Facebook App settings page.

    Login & Get Facebook Account Data (index.php)

    In this file, the Facebook API authentication process is handled using PHP.

    setDefaultAccessToken ($_SESSION [ "facebook_access_token" ]); }else{ // Put short-lived access token in session $_SESSION [ "facebook_access_token" ] = (string) $accessToken ; // OAuth 2.0 client handler helps to manage access tokens $oAuth2Client = $fb -> getOAuth2Client (); // Exchanges a short-lived access token for a long-lived one $longLivedAccessToken = $oAuth2Client -> getLongLivedAccessToken ($_SESSION [ "facebook_access_token" ]); $_SESSION [ "facebook_access_token" ] = (string) $longLivedAccessToken ; // Set default access token to be used in script $fb -> setDefaultAccessToken ($_SESSION [ "facebook_access_token" ]); } // Redirect the user back to the same page if url has "code" parameter in query string if(isset($_GET [ "code" ])){ header ("Location: ./" ); } // Getting user"s profile info from Facebook try { $graphResponse = $fb -> get ("/me?fields=name,first_name,last_name,email,link,gender,picture" ); $fbUser = $graphResponse -> getGraphUser (); } catch(FacebookResponseException $e ) { echo "Graph returned an error: " . $e -> getMessage (); session_destroy (); // Redirect user back to app login page header ("Location: ./" ); exit; } catch(FacebookSDKException $e ) { echo "Facebook SDK returned an error: " . $e -> getMessage (); exit; } // Initialize User class $user = new User (); // Getting user"s profile data $fbUserData = array(); $fbUserData [ "oauth_uid" ] = !empty($fbUser [ "id" ])? $fbUser [ "id" ]: "" ; $fbUserData [ "first_name" ] = !empty($fbUser [ "first_name" ])? $fbUser [ "first_name" ]: "" ; $fbUserData [ "last_name" ] = !empty($fbUser [ "last_name" ])? $fbUser [ "last_name" ]: "" ; $fbUserData [ "email" ] = !empty($fbUser [ "email" ])? $fbUser [ "email" ]: "" ; $fbUserData [ "gender" ] = !empty($fbUser [ "gender" ])? $fbUser [ "gender" ]: "" ; $fbUserData [ "picture" ] = !empty($fbUser [ "picture" ][ "url" ])? $fbUser [ "picture" ][ "url" ]: "" ; $fbUserData [ "link" ] = !empty($fbUser [ "link" ])? $fbUser [ "link" ]: "" ; // Insert or update user data to the database $fbUserData [ "oauth_provider" ] = "facebook" ; $userData = $user -> checkUser ($fbUserData ); // Storing user data in the session $_SESSION [ "userData" ] = $userData ; // Get logout url $logoutURL = $helper -> getLogoutUrl ($accessToken , FB_REDIRECT_URL . "logout.php" ); // Render Facebook profile data if(!empty($userData )){ $output = "

    Facebook Profile Details

    "
    ; $output .= "
    " ; $output .= "" ; $output .= "

    Facebook ID: " . $userData [ "oauth_uid" ]. "

    " ; $output .= "

    Name: " . $userData [ "first_name" ]. " " . $userData [ "last_name" ]. "

    " ; $output .= "

    Email: " . $userData [ "email" ]. "

    " ; $output .= "

    Gender: " . $userData [ "gender" ]. "

    " ; $output .= "

    Logged in with: Facebook

    "
    ; $output .= "

    Profile Link: . $userData [ "link" ]. "" target="_blank">Click to visit Facebook page

    "
    ; $output .= "

    Logout from Facebook

    " ; $output .= "
    " ; }else{ $output = "

    Some problem occurred, please try again.

    "
    ; } }else{ // Get login url $permissions = [ "email" ]; // Optional permissions $loginURL = $helper -> getLoginUrl (FB_REDIRECT_URL , $permissions ); // Render Facebook login button $output = """>" ; } ?> <html lang ="en-US" > <head > <title > Login with Facebook using PHP by CodexWorldtitle > <meta charset ="utf-8" > head > <body > <div class ="container" > <div class ="fb-box" > div > div > body > html >

    Logout (logout.php)

    If the user wishes to log out from their Facebook account, the logout.php file is loaded.

    • Remove access token and user data from the SESSION.
    • Redirect the user to the homepage.
    // Remove access token from session unset($_SESSION [ "facebook_access_token" ]); // Remove user data from session unset($_SESSION [ "userData" ]); // Redirect to the homepage header ("Location:index.php" ); ?>

    Conclusion

    In this tutorial, we’ve tried to make Facebook Login implementation quicker and easier. The example code integrates Facebook Login with the Facebook SDK for PHP. You don’t need to add the SDK library files separately, our source code contains all the required files with the SDK v5 for PHP. You only need to specify some minimal settings for adding login system with Facebook to your website using PHP. To make the Facebook login more user-friendly, you can use JavaScript SDK to integrate .

    Are you want to get implementation help, or modify or extend the functionality of this script?

    Facebook is the most popular social media and shares on the Facebook wall are the most used activity by its user. Facebook share option is a common and required feature for every web application. We can easily share the post on Facebook by manually or from the script. In this tutorial, you’ll learn how to post activity on Facebook wall from website using PHP and Facebook API.

    Post to Facebook wall is useful when you want to post dynamic content to Facebook from the website. Here we’ll build a simple PHP script to publish Facebook post from website using Facebook PHP SDK. This functionality lets the user submit the post (message, picture, link, text content) on their Facebook timeline from the website using PHP SDK v5.0 and Facebook Graph API .

    Before getting started to post to Facebook wall using PHP, take a look at the files and folders structure.

    Facebook Apps Creation

    To access Facebook API, App ID & App Secret need to be specified on Facebook API call. You need to create a Facebook App for generating App ID & App Secret. If you’re not already created a Facebook app, visit the link below to create and configure a Facebook App from the App Dashboard .

    After completing the Facebook App creation and configuration you’ll get the App ID and App secret. Copy this App ID and App Secret of your Facebook App for later use.

    Facebook SDK for PHP v5.0

    All Facebook PHP SDK files are included in the facebook-php-sdk/ directory, place the facebook-php-sdk/ folder into the root directory. You don’t need to download it separately, Facebook SDK v5 is included in our source code.

    Facebook API Configuration (fbConfig.php)

    The fbConfig.php file is used to configure Facebook SDK and connect to Facebook Graph API. Specify your Facebook App ID ($appId), App Secret ($appSecret), Callback URL ($redirectURL), and Permissions ($fbPermissions) to connect with Facebook API and working with SDK.

    Note that: The access token must have the publish_actions permission to post on Facebook wall.

    if(! session_id ()){
    session_start ();
    }// Include the autoloader provided in the SDK
    require_once __DIR__ . "/facebook-php-sdk/autoload.php" ;// Include required libraries
    use Facebook \ Facebook ;
    use Facebook \ Exceptions \ FacebookResponseException ;
    use Facebook \ Exceptions \ FacebookSDKException ;/*
    * Configuration and setup Facebook SDK
    */
    $appId = "InsertAppID" ; //Facebook App ID
    $appSecret = "InsertAppSecret" ; //Facebook App Secret
    $redirectURL = "http://localhost/post_to_facebook_from_website/" ; //Callback URL
    $fbPermissions = array("publish_actions" ); //Facebook permission$fb = new Facebook (array(
    "app_id" => $appId ,
    "app_secret" => $appSecret ,
    "default_graph_version" => "v2.6" ,
    ));// Get redirect login helper
    $helper = $fb -> getRedirectLoginHelper ();// Try to get access token
    try {
    $accessToken = $_SESSION [ "facebook_access_token" ];
    }else{
    $accessToken = $helper -> getAccessToken ();
    }
    } catch(FacebookResponseException $e ) {
    echo "Graph returned an error: " . $e -> getMessage ();
    exit;
    } catch(FacebookSDKException $e ) {
    echo . $e -> getMessage ();
    exit;
    }
    ?>

    Note that: You’ll find the App ID and App Secret on your Facebook Apps settings page.

    Submit Post to Facebook Wall (index.php)

    Include the fbConfig.php file to connect Facebook API and get the access token.

    If FB access token ($accessToken) is available, the following will happen.

    If FB access token ($accessToken) is not available, the Facebook Login URL will be generated and the user would be redirected to the FB login page.

    // Include FB configuration file
    require_once "fbConfig.php" ;$accessToken )){
    if(isset($_SESSION [ "facebook_access_token" ])){
    $fb ->
    }else{
    // Put short-lived access token in session
    $_SESSION [ "facebook_access_token" ] = (string) $accessToken ;// OAuth 2.0 client handler helps to manage access tokens
    $oAuth2Client = $fb -> getOAuth2Client ();// Exchanges a short-lived access token for a long-lived one
    $longLivedAccessToken = $oAuth2Client -> getLongLivedAccessToken ($_SESSION [ "facebook_access_token" ]);
    $_SESSION [ "facebook_access_token" ] = (string) $longLivedAccessToken ;// Set default access token to be used in script
    $fb -> setDefaultAccessToken ($_SESSION [ "facebook_access_token" ]);
    }//FB post content
    $message = "Test message from сайт website" ;
    $title = "Post From Website" ;
    $link = "http://www.сайт/" ;
    $description = "CodexWorld is a programming blog." ;
    $picture = "http://www..png" ;$attachment = array(
    "message" => $message ,
    "name" => $title ,
    "link" => $link ,
    "description" => $description ,
    "picture" => $picture ,
    );// Post to Facebook
    $fb -> post ("/me/feed" , $attachment , $accessToken );// Display post submission status
    echo "The post was published successfully to the Facebook timeline." ;
    }catch(FacebookResponseException $e ){
    echo "Graph returned an error: " . $e -> getMessage ();
    exit;
    }catch(FacebookSDKException $e ){
    echo "Facebook SDK returned an error: " . $e -> getMessage ();
    exit;
    }
    }else{
    // Get Facebook login URL
    $fbLoginURL = $helper -> getLoginUrl ($redirectURL , $fbPermissions );

    // Redirect to Facebook login page
    echo """>" ;
    }

    Conclusion

    We’ve tried to provide a simple way to share the post to Facebook wall from website using PHP . Hope! our script will help you to post on Facebook wall from your website. Also, you can change the post content dynamically by specifying the respective value in $attachment array.

    Are you want to get implementation help, or modify or extend the functionality of this script?

    Абсолютно используйте 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")); } } }

    isLoggedIn()): ?> 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(); }

    Connecting FB accounts with accounts on my website

    Please help me or just give me a hint where should I start, because I"ve been fighting with this for 2 weeks. As we all know, facebook has a new auth system which means I have to implement it on my website and I just can"t understand how it works and how to implement it on my website. Of course I know there are examples over the Internet and on Developers page - I had read them all and still don"t know how to acheive linking accounts on my website with FB accounts. Maybe I will present some situations I need to cover: The website has local accounts. There is an additional DB table which can link my user ids with FB user ids. Situation 1: a new person comes to my website. He/She does not have my website"s account but does have FB account. He/She clicks on "Login with facebook", gets redirected to FB, authorizes the app and gets redirected back to my website which creates a new user account and connects my website"s uid with authed FB uid. Situation 2: a person has an account on my website, already connected to some FB account. He/She clicks on "Login with facebook", my website finds FB uid in "link" table and logs in the user which is connected to that FB account. Situation 3: a person has an account on my website which is not connected to any FB account. He/She goes to a special panel on my website with a link "Connect this account with Facebook". He/She clicks on it, authorizes the app, gets redirected back to my website which creates a record in "link" table connecting website"s uid with facebook uid. After making the connection that special panel shows an info "Your are connected to facebook account. ". Situation 4: a person is logged in to my website to an account which is connected to Facebook account. He/She does some actions on my website which result in posting messages on his/her FB wall. So TL;DR, a normal functionality of making a bound between FB accounts and accounts on my website. With previous API everything was fine and working, there was also offline_access I could use for posting on wall, there was no tokens for that etc., you know. Right now.. I don"t know where to start, where and how I should store these tokens, how to get them and on what occasions, how to link exiting accounts, how to "update" existing "bounds" in my "link" table. Just simple hints in pseudocode or a list of 1..2..3.. steps how this flow should look like would be really helpful guys because I can"t find any helping information on the Internet. Every "example" or "tutorial" for this new API tells how to just authenticate FB account on your website but not how to really connect these accounts to something or store this connection for example in the database. I use latest PHP Facebook SDK.

    Related Links

    SQLSTATE Connection refused with right port
    Laravel 5.2 routing like cakephp
    How to get a link then take some characters out? PHP
    Change database setup now having error even after reverting to orginal setup (Laravel 5)

    © 2024 who-calls-me.ru
    Whocallsme - Мир вашего софта