Login with Twitter using PHP

Twitter is one of the most popular social network on the internet and millions of users are registered with twitter. With twitter you can increase user registration at your site. Twitter API provides an easy way to allow your website visitors to login with their twitter account at your site. Nowadays users are not interested to filling the big registration forms. Twitter Login API helps to solve this problem.

Twitter oAuth PHP library helps web developer to integrate twitter login system by quick, easy and powerful way. This Login with Twitter API tutorial will explain how to implement users sign in with Twitter using PHP and store the user informations into the MySQL database. We will discuss about implementing sign in with twitter using PHP and Twitter Apps creation process. We have used Twitter OAuth PHP library to support OAuth for Twitter’s REST API.

From the above Demo links you would be able to view the live demo of the project. Also you can download the full source code of PHP login with Twitter API from the above Download link and implement the twitter login system within a minute.


This project contains three folders named inc/, includes/ and images/ with some PHP files. The folders and files structure are given below:

  • inc/
    • OAuth.php
    • twitteroauth.php
  • includes/
    • functions.php
  • process.php
  • config.php
  • index.php
  • logout.php
  • images/

Twitter Apps Creation:

 At first go to the https://apps.twitter.com/app/new and login at your Twitter developer account.
 Create new apps with the following details.

  • Name: Your application Name. This is shown to the user while authorizing.
  • Description: Your application Description. This is shown to user while authorizing.
  • Website: Your application website.
  • Callback URL(*): After authorization, this URL is called with oauth_token.

 Now change the apps permission to Read and Write or Read, Write and Access direct messages. For change the apps permission, you need to add mobile number to your twitter account. If you are not able to add mobile number from the web, then please follow the below steps.

  • In order to use this process, you need to have a smart phone and install the Twitter mobile application. By this process you will be able to switch to Twitter application write access, although the Twitter websites doesn’t accept your phone number.
  • After installing the Twitter mobile application, go to the tab on the right, it’s the screen showing your user details. Hit the wheel (it’s shown under the amount of tweets) and click Settings.
  • After clicking on Settings, another view opens where you have to click on your account.
  • The following view shows the options for your Account – scroll all the way down and click Security.
  • After hitting the Security option, the application will ask you to add a phone.
  • After clicking Add phone, the mobile browser will open and require you to insert your phone number.
  • After adding the phone number and pressing save, wait a few minutes. Twitter will send you a link to the phone number you just added to verify it. After clicking the link in the SMS the phone number is approved and you should be able to switch the application access to write.

 After the apps creation you have to click on Test OAuth. Also you should login with your twitter account for test OAuth. After that you would be redirected to the OAuth Settings page. At the OAuth Settings page you can see the Consumer key and Consumer secret.
 Congratulation! your apps creation has completed.

Database table creation:

To store the user information, you need to create a database and a table. At first create a database like codexworld. After that copy the below SQL query and run the SQL query on the database.

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `fname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `lname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
    `oauth_token` text COLLATE utf8_unicode_ci NOT NULL,
    `oauth_secret` text COLLATE utf8_unicode_ci NOT NULL,
    `picture` varchar(255) 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


In this project you just have to modify only two files.
 Database configuration (includes/functions.php):functions.php file have Users class with some functions. Into the __construct() function we have configured the database and connect with the database. You need only to change the $dbServer, $dbUsername, $dbPassword and $dbName variables value with your MySQL server details.

  • function __construct(){
    //database configuration
    $dbServer 'localhost'//Define database server host
    $dbUsername 'root'//Define database username
    $dbPassword ''//Define database password
    $dbName 'codexworld'//Define database name
        //connect databse
    $con mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
    "Failed to connect with MySQL: ".mysqli_connect_error());
    $this->connect $con;

 Twitter API configuration (config.php): open the config.php file and modify the CONSUMER_KEY, CONSUMER_SECRET and OAUTH_CALLBACK constants value.
Note that: You can find the CONSUMER_KEY and CONSUMER_SECRET at the app page.(Go to the https://apps.twitter.com => click on your app => click on the API Keys tab => copy the API key and API secret => replace CONSUMER_KEY value with API key and CONSUMER_SECRET value with API secret)

  • define('CONSUMER_KEY''Twitter Consumer Key');
    define('CONSUMER_SECRET''Twitter Consumer Secret');

Getting User Email from Twitter Account

Basically, Twitter doesn’t return the user email after authentication. To get the user’s Email Address, your application needs to be whitelisted by Twitter. To get and store the user email address, follow the below steps.

  • Use this form to submit your request. It will take some times please be patient.
  • Once whitelisted, the Request email addresses from users checkbox will be available under your app permission on Application Management. Under settings, Privacy Policy URL and Terms of Service URL fields will be available. If enabled, users will be informed that your app can access their email on the OAuth dialog.
  • Open the process.php file and use include_email parameter in get() function. To do that replace $user_info variable line value with the following line of code (probably line no. 25).
    $user_info $connection->get('account/verify_credentials', ['include_email' => 'true']);

    Now you can get the user email address using $user_info->email.

  • Add a new field (email) to store user email in the users table. Also, you can run the following SQL on users table at the database.
    ALTER TABLE `users` ADD `email` VARCHAR(100) NOT NULL AFTER `lname`;
  • Open the includes/functions.php file and add $email parameter to the checkUser() function. Modify the INSERT and UPDATE query with email column name and value.
    function checkUser($oauth_provider,$oauth_uid,$username,$fname,$lname,$email,$locale,$oauth_token,$oauth_secret,$profile_image_url){
    $prevQuery mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
    mysqli_num_rows($prevQuery) > 0){
    $update mysqli_query($this->connect,"UPDATE $this->tableName SET oauth_token = '".$oauth_token."', oauth_secret = '".$oauth_secret."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
    $insert mysqli_query($this->connect,"INSERT INTO $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."', username = '".$username."', fname = '".$fname."', lname = '".$lname."', email = '".$email."', locale = '".$locale."', oauth_token = '".$oauth_token."', oauth_secret = '".$oauth_secret."', picture = '".$profile_image_url."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'") or die(mysqli_error($this->connect));
    $query mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
    $result mysqli_fetch_array($query);
  • Open the process.php file and pass the Twitter account email to checkUser() function once user logged in.

 If you have any query about this tutorial and scripts, feel free to comment here.

Recommended Tutorials For You


  1. Mrutyunjaya Behera Said...
  2. Parul Said...
  3. Ibrahim Said...
  4. Arsh Said...
  5. Gurpreet Said...
  6. Jeena Said...
  7. Jo Miller Said...
    • CodexWorld Said...
  8. Jo Miller Said...
  9. Jayendra Said...
    • CodexWorld Said...
  10. Jayendra Said...
  11. Gaurav Said...
  12. Nirav Said...
  13. Parag Said...
  14. Parag Said...
    • CodexWorld Said...
  15. Alex Said...
  16. Valentin Said...
  17. Khalid Said...
  18. Duwi Said...
    • CodexWorld Said...
  19. Dharmendra Said...
    • CodexWorld Said...
  20. Gaurav Pachani Said...
  21. Freddy Sidauruk Said...
  22. Freddy Sidauruk Said...
    • CodexWorld Said...

Leave a reply