Thursday 10 July 2014

How to Integrate login with LinkedIn oAuth in PHP


Now a days popular sites provide api so that we can integrate in our sites and get there information on one click no more fill complex forms etc. Today i am going to explain you how to integrate with LinkedIn one of the most popular website.

Make New Application on LinkedIn:

1.visit https://www.linkedin.com/secure/developer and click Add New Application.

Fill all information of your application.

Company Info
-------------
Company :
  Company Name :
  Account Administrator :

Application Info
----------------
       Application Name :
            Description :
        Integration URL :
       Application Type :
            Live Status :


Now, You'll get linkedin API key and Secret Key

Programming Time:
The script contains two folders called oAuth and images with PHP files.

oauth
- class.linkedClass.php // Class Get user Information
- config.php // Configuration file
- linkedinoAuth.php // Call methods
- OAuth.php // Twitter OAUTH library

images

linkedinauth.php //Call back page Show details
html.inc // html design view
index.php // Main index file show data
linkedin.php // Redirect to linkedin for authorization

PHP Code
---------

<?php
$config['base_url']             =   'http://demo.phptipsntricks.com/';
$config['callback_url']         =   'http://demo.phptipsntricks.com/index.php';

//linkedin configuration
$config['linkedin_access']      =   'your_linkedin_access';
$config['linkedin_secret']      =   'your_linkedin_secret';
$config['linkedin_library_path']=   'linkedinoAuth.php';
?>


Index.php
-----------
Shows a button for linkedin authorization if not authorized.

Redirect you to linkedin.php generate token and redirect to linkedin app authorization page.

<?php
    session_start();
    include_once 'oAuth/config.php';
    include_once 'oAuth/linkedinoAuth.php';

    # First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
    $linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['base_url'] . 'linkedin_login_oauth/linkedinauth.php' );
    // $linkedin->debug = true;

    # Now we retrieve a request token. It will be set as $linkedin->request_token
    $linkedin->getRequestToken();
    $_SESSION['requestToken'] = serialize($linkedin->request_token);

    # With a request token in hand, we can generate an authorization URL, which we'll direct the user to
    ## echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
    header("Location: " . $linkedin->generateAuthorizeUrl());
?>

Once you Allow access it will redirect you on linkedinauth.php (defined in linkedin.php) and show all data of authorized user.

How to Login with Facebook Graph API in PHP


I have been working on facebook apps and connection with Facebook Graph API access tocken. This post will explain you how to integrate facebook connect in your website in easy way to connect and read the Facebook home timeline with PHP. Explained how to get facebook token and user id hope you like it. Thanks !

Make New Application on Facebook:

1. Visit <a href="https://developers.facebook.com/apps">https://developers.facebook.com/apps</a> and click + Create New App.

The script contains two folders called oAuth and images with PHP files.

src

- base_facebook.php // Class Get user Info
- facebook.php // Class Get user Info
- config.php // Configuration file

images
html.inc // html design view
index.php // Main index file show data

PHP Code
-----------
<?php

$config['callback_url']         =   'CALL BACK URL/?fbTrue=true'; //    /?fbTrue=true allow you to code process section.

//Facebook configuration
$config['App_ID']      =   'Your App ID';
$config['App_Secret']  =   'Your App Secret';

?>


Index.php
----------

While clicking Login with Facebook button URL requesting Facebook Graph API with contains your web project redirection URL:

$config['callback_url'] = "http://www.yoursite.com/index.php/?fbTrue=true"; // added in config.php

<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>


<?php
require 'src/config.php';
require 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $config['App_ID'],
  'secret' => $config['App_Secret'],
  'cookie' => true
));

if(isset($_GET['fbTrue']))
{
    $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url'])
       . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code'];

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

     $graph_url = "https://graph.facebook.com/me?access_token="
       . $params['access_token'];

     $user = json_decode(file_get_contents($graph_url));
     $content = $user;
}
else
{
    $content = '<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>';
}

include('html.inc');
?>

Force to download a file in PHP


In this tutorial we have simple script to download files by force instead of open it in browser window. This is useful for common file types that would normally be displayed in a browser .csv, .php and all types of images( gif, png, jpg etc. ).

<?php
function output_file($Source_File, $Download_Name, $mime_type='') {
/*
$Source_File = path to a file to output
$Download_Name = filename that the browser will see
$mime_type = MIME type of the file (Optional)
*/
if(!is_readable($Source_File)) die('File not found or inaccessible!');

$size = filesize($Source_File);
$Download_Name = rawurldecode($Download_Name);

/* Figure out the MIME type (if not specified) */
$known_mime_types=array(
   "pdf" => "application/pdf",
   "csv" => "application/csv",
   "txt" => "text/plain",
   "html" => "text/html",
   "htm" => "text/html",
   "exe" => "application/octet-stream",
   "zip" => "application/zip",
   "doc" => "application/msword",
   "xls" => "application/vnd.ms-excel",
   "ppt" => "application/vnd.ms-powerpoint",
   "gif" => "image/gif",
   "png" => "image/png",
   "jpeg"=> "image/jpg",
   "jpg" =>  "image/jpg",
   "php" => "text/plain"
);

if($mime_type==''){
    $file_extension = strtolower(substr(strrchr($Source_File,"."),1));
    if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
    }
    else {
$mime_type="application/force-download";
    };
};

@ob_end_clean(); //off output buffering to decrease Server usage

// if IE, otherwise Content-Disposition ignored
if(ini_get('zlib.output_compression'))
 ini_set('zlib.output_compression', 'Off');

header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$Download_Name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');

header("Cache-control: private");
header('Pragma: private');
header("Expires: Thu, 26 Jul 2012 05:00:00 GMT");

// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE'])) {
   list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
   list($range) = explode(",",$range,2);
   list($range, $range_end) = explode("-", $range);
   $range=intval($range);
   if(!$range_end) {
$range_end=$size-1;
   }
   else {
$range_end=intval($range_end);
   }

   $new_length = $range_end-$range+1;
   header("HTTP/1.1 206 Partial Content");
   header("Content-Length: $new_length");
   header("Content-Range: bytes $range-$range_end/$size");
}
else {
   $new_length=$size;
   header("Content-Length: ".$size);
}

/* output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($Source_File = fopen($Source_File, 'r')) {
   if(isset($_SERVER['HTTP_RANGE']))
   fseek($Source_File, $range);

   while(!feof($Source_File) && (!connection_aborted()) && ($bytes_send<$new_length)) {
$buffer = fread($Source_File, $chunksize);
print($buffer); //echo($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
   }
fclose($Source_File);
}
else {
die('Error - can not open file.');
}

die();
}
?>

<?php
include("function.php");
set_time_limit(0);
$file_path="phpgang.csv";
output_file($file_path, 'phpgang.csv', 'application/csv');
?>

Send Email with SMTP and PHP Mailer

In this tutorial we have a simple script which send email through SMTP (Send Mail Transfer protocol) with PHP Mailer. We need <a href="http://phpmailer.worxware.com/">phpmailer</a> library and bellow given code.

<?php
    require_once('PHPMailer_v5.1/class.phpmailer.php'); //library added in download source.
    $msg  = 'Hello World';
    $subj = 'test mail message';
    $to   = 'info@site.com';
    $from = 'you@youremail.com';
    $name = 'My Name';

    echo smtpmailer($to,$from, $name ,$subj, $msg);

    function smtpmailer($to, $from, $from_name = 'Example.com', $subject, $body, $is_gmail = true) {
        global $error;
        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true;
        if($is_gmail) {
            $mail->SMTPSecure = 'ssl';
            $mail->Host = 'smtp.gmail.com';
            $mail->Port = 465;
            $mail->Username = 'admin@example.com';
            $mail->Password = '*******';  
        }
        else {
            $mail->Host = 'smtp.mail.google.com';
            $mail->Username = 'admin@example.com';
            $mail->Password = '******';
        }
        $mail->IsHTML(true);
        $mail->From="admin@example.com";
        $mail->FromName="Example.com";
        $mail->Sender=$from; // indicates ReturnPath header
        $mail->AddReplyTo($from, $from_name); // indicates ReplyTo headers
        $mail->AddCC('cc@site.com.com', 'CC: to site.com');
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AddAddress($to);
        if(!$mail->Send()) {
            $error = 'Mail error: '.$mail->ErrorInfo;
            return true;
        }
        else {
            $error = 'Message sent!';
            return false;
        }
    }
?>

How to manage international languages in MySQL database


If you are making a web site where multiple languages used like Arabic, French, Hindi or Urdu then your MySQL database default settings is not valid to do that to insert all languages in database. If you insert data in your database and database is not configured as I am going to show you in this tutorial then your data will be look like ????? and you lost your data.

So now i am going to tell you how to configure database to accept international languages.

Very important HTML settings you have to add a meta for character set UTF-8

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Now create table in your database its default character set will be <strong>latin1_swedish_ci</strong>

You have to change it to <strong>utf8_general_ci</strong>

Here is the insert query

mysql_query("INSERT INTO `comments`(id,comment) values (N'$id',N'$comment')");

N’$id’ N is stands for national regional language character set.

Fetch code and query

<?php
include('db.php');
mysql_query("set character_set_results='utf8'");
---- code ---
?>

Now your database is configured to insert all international languages.

How to Integrate Paypal Payment System in PHP & MySQL

I received a tutorial requests from my reader that asked to me how to implement payment gateway system with Paypal API. In this tutorial I want to explain how to work with Paypal Sandbox test accounts for payment system development and sending arguments while click buy now button. It’s simple and very easy to integrate in your web projects.



Step 1
-------
Create a Paypal Sandbox account at https://developer.paypal.com/

Step 2
------
Now create test accounts for payment system. Take a look at Sandbox menu left-side top Sandbox->Test Accounts



Step 3
-------
Here I have created two accounts Buyer (personal) and Seller (merchant/business)



index.php
-----------
Contains PHP code. Displaying products, product image, product name and product price. Here you have to give your business(seller) $paypal_id id. Modify paypal button form return and cancel_return URLs.

<?php
$paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr'; // Test Paypal API URL
$paypal_id='your_seller_id'; // Business email ID
?>
<h4>Welcome, Guest</h4>

<div class="product">          
    <div class="image">
        <img src="http://www.phpgang.com/wp-content/uploads/gang.jpg" />
    </div>
    <div class="name">
        PHPGang Payment
    </div>
    <div class="price">
        Price:$10
    </div>
    <div class="btn">
    <form action="<?php echo $paypal_url; ?>" method="post" name="frmPayPal1">
    <input type="hidden" name="business" value="<?php echo $paypal_id; ?>">
    <input type="hidden" name="cmd" value="_xclick">
    <input type="hidden" name="item_name" value="PHPGang Payment">
    <input type="hidden" name="item_number" value="1">
    <input type="hidden" name="credits" value="510">
    <input type="hidden" name="userid" value="1">
    <input type="hidden" name="amount" value="10">
    <input type="hidden" name="cpp_header_image" value="http://www.phpgang.com/wp-content/uploads/gang.jpg">
    <input type="hidden" name="no_shipping" value="1">
    <input type="hidden" name="currency_code" value="USD">
    <input type="hidden" name="handling" value="0">
    <input type="hidden" name="cancel_return" value="http://demo.phpgang.com/payment_with_paypal/cancel.php">
    <input type="hidden" name="return" value="http://demo.phpgang.com/payment_with_paypal/success.php">
    <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
    <img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
    </form>
    </div>
</div>

success.php
-------------
Paypal payment success return file. Getting Paypal argument like item_number. Paypal data success.php?tx=83437E384950D&st=Completed&amt=10.00&cc=USD&cm=&item_number=1

<?php
$item_no            = $_REQUEST['item_number'];
$item_transaction   = $_REQUEST['tx']; // Paypal transaction ID
$item_price         = $_REQUEST['amt']; // Paypal received amount
$item_currency      = $_REQUEST['cc']; // Paypal received currency type

$price = '10.00';
$currency='USD';

//Rechecking the product price and currency details
if($item_price==$price && $item_currency==$currency)
{
    echo "<h1>Welcome, Guest</h1>";
    echo "<h1>Payment Successful</h1>";
}
else
{
    echo "<h1>Payment Failed</h1>";
}

cancel.php
-----------

Paypal API cancel_return file.

<?php
echo "<h1>Welcome, Guest</h1>";
echo "<h1>Payment Canceled</h1>";
?>

Step 4
--------
When your web application test payment system workflow is completed. Change the form action development API URLs to original API URLs and give valid $paypal_id seller email id.

$paypal_url='https://www.sandbox.paypal.com/cgi-bin/webscr';
//to
$paypal_url='https://www.paypal.com/cgi-bin/webscr';