Personal Project

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, November 22, 2016

How to setup a load balancing and failover back-end RDS for WordPress ?

WordPress is widely used to develop webs for multiple platforms. 
It is necessary to set up WordPress to deploy on a load balancing and failover backend RDS if you want to provide a service without any downtime for your customers.

How to get this  done ?

1. Create a Master and Slave database on RDS.

2.Import HyperDB Plugin into WordPress folder.

HyperDB can be download at below.
https://wordpress.org/plugins/hyperdb/


3. Setup the Master and Salve URL at HyperDB`s config file.


4. Performance Test 

The following info shows the test result on AWS.

EC2         Current session                RDS                                           
t2.micro            110 / s                     single master        
t2.medium         210 /s                       one master and one slave    


To conclude, using WordPress framework to develop the website can achieve a high performance at 210 current requests per second on EC2 with t2.medium spec; with t2.micro of EC2, the best throughput can also achieve 110 current requests per second. Thus, I think WordPress is good enough to build a high-performance website by PHP on AWS.


Thursday, June 2, 2016

How to get Video Info by using Youtube Datat API ?

Get Started

Youtube Data API has provided an HTTP interface to retrieve plenty of counter numbers to record who has seen or voted for your video. You simply send a GET request shown below to youtube and will get all the information related to your video.

GET Request

https://www.googleapis.com/youtube/v3/videos?id=[VIDEO ID]&key=[ API KEY]&fields=items%28id,snippet%28channelTitle,title,thumbnails%29,statistics%29&part=snippet,contentDetails,statistics

VIDEO ID is a unique key to identify the Video.
API KEY   is the key which you must create a service to use Youtube Data API at Google Developer API Console.

How to implement this feature in PHP ?

Send a GET Request to Youtube

 The function below shows how to send a GET request to Youtube by using Youtube Data  API.
function getYoutubeInfo($videoId, $key)
    {       
        // Get cURL resource
        $curl = curl_init();
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => 'https://www.googleapis.com/youtube/v3/videos?id='.$videoId.'&key='.$key.'&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics',
            CURLOPT_USERAGENT => 'Your Agent Name'
        ));
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
       
        $resp = json_decode($resp, true);
           
        if(!isset($resp['code']))
        {
            if(isset($resp['items']))
            {
                foreach ($resp['items'] as $data)
                {
                    $dataArray = array();
                    $dataArray = $data['snippet'];                                   
                                   
                    $tmpArray = $data['statistics'];
                    //  You can get ViewCount, likeCount, and CommentCount here
                    error_log("### get respond viewCount:" . $tmpArray['viewCount']. " likeCount" . $tmpArray['likeCount']. " commentCount:" .$tmpArray['commentCount']);               
               
                    //  You can get the image url of your video
                    return $dataArray['thumbnails'];

                }
            }
        }   
        // Close request to clear up some resources
        curl_close($curl);
        return;
    }






Thursday, May 12, 2016

How to validate Store Receipt for Apple Store and Google Play using Unity and PHP ?

Get Started

This tutorial will teach you how to validate Store receipt for Google Play and Apple Store using PHP and Unity.  You have to upload the PHP (verifyReceipt.php) to your server and set up the Unity plugin and add the following sample codes.

Import Unity Prime31 Plugin

Import Prime31 plugins StoreKit for Apple Store and In-App-Billing for Google Play into Unity.

How to setup In-App-Purchase for IOS ?

There are two steps for this.
  • Setup Item`s Product Id
  • Setup Payment Success Event to Get Receipt

Setup Item`s Product Id

Open a demo scene in folder
  /Plugins/Prime31/Storekit/demo/StoreKitTestScene.
Edit StoreKitGUIManager.cs and modify Product Id.
 /Plugins/Prime31/Storekit/demo/ StoreKitGUIManager.cs

 // XXXX is the product Id, which must match what you have in iTunes.
 var productIdentifiers = new string[] { "XXXX" };
 StoreKitBinding.requestProductData( productIdentifiers );

Setup Payment Success Event to Get Receipt

The following function aims to capture the receipt from Apple when the payment becomes successful, and send the receipt to PHP to validate the receipt`s correctness.
Edit /Plugins/Prime31/Storekit/demo/ StoreKitEventListener.cs

void purchaseSuccessfulEvent( StoreKitTransaction transaction )
   {
       Debug.Log( "purchaseSuccessfulEvent: " + transaction );

       // Get iOS receipt 
       string receipt = transaction.base64EncodedTransactionReceipt;

       // Build POST form
       WWWForm form = new WWWForm ();
       form.AddField ("key", "1234");
       form.AddField ("receipt", receipt);
       form.AddField ("en", "prod") // dev, prod
       form.AddField ("os", "ios")  // ios, android

       // Server URL
       string url = "http://your server IP/verifyPayment.php";

       // Process respond
       StartCoroutine(this.DoWWW(new WWW(url, form), (www) => {
           Debug.Log("-------- Callback Success: " + www.text);
       }));
   }

How to setup In-App-Billing for Android ?

There are two steps for this.
  • Setup App Public Key
  • Setup Item`s Product Id
  • Setup Payment Success Event to Get Receipt

Setup App Public Key

Open a demo scene in folder
/Plugins/ InAppBillingAndroid /demo/IABTestScene.unity
Setup Public key
Edit /Plugins/ InAppBillingAndroid /demo/ IABUIManager.cs

// Setup Public key 
var key = "Your Public Key on Google Play";

GoogleIAB.init( key );

Setup Item`s Product Id

Edit /Plugins/ InAppBillingAndroid /demo/ IABUIManager.cs

// Setup Product ID 
private string[] skus = new string[] 
{
    "XXXXXX"  //  your Product Id here 
};

GoogleIAB.queryInventory( skus );

Setup Payment Success Event to Get Receipt

Edit /Plugins/ InAppBillingAndroid /demo/ GoogleIABEventListener.cs


void purchaseCompleteAwaitingVerificationEvent( string purchaseData, string signature )
{
    Debug.Log( "purchaseCompleteAwaitingVerificationEvent. purchaseData: " + purchaseData + ", signature: " + signature );
    Prime31.Utils.logObject (purchaseData);
    Prime31.Utils.logObject (signature);

    // Google receipt 
    string receipt = purchaseData;

    // Initil POST form
    WWWForm form = new WWWForm ();
    form.AddField ("key", "1234");
    form.AddField ("os", "android");
    form.AddField ("en", "prod");
    form.AddField ("receipt", receipt);
    form.AddField ( "sing", signature);

    // Server URL
    string url = "http://your server ip/veryPayment.php";
    // Process respond
    StartCoroutine (this.DoWWW (new WWW (url, form), (www) => 
    {
        Debug.Log("-------- Callback Success: " + www.text);
    }));
}

Wednesday, March 2, 2016

Send Email in PHP with Japanese subject and body


   Before, we get started, you must have an SMTP server that can receive the emails from your machines 

   and send them to the recipient

    (i.e. your corporate exchange or Gmail).

 

    How to Setup Email on Linux Using Gmail and SMTP

  • Install ssmtp 

    sudo apt-get install ssmtp

    Edit ssmtp file

    sudo vim /etc/ssmtp/ssmtp.conf
  • root=username@gmail.com
    mailhub=smtp.gmail.com:465
    rewriteDomain=gmail.com
    AuthUser=username@gmail.com
    AuthPass=password
    FromLineOverride=YES
    UseTLS=YES

In order to make the default (root) “from” field be the server name, edit the/etc/ssmtp/revaliases file:
sudo vim /etc/ssmtp/revaliases
And add into it the desired translation which in our Gmail examples case will be:
root:username@gmail.com:smtp.gmail.com:465
Incredibly this is all you have to do to enable the ability. From now on, the machine will Email you when something is up.

Test Email Command

Lets test that our ssmtp setup was correct by sending an Email:

echo "Test message from Linux server using ssmtp" | sudo ssmtp -vvv your-email@some-domain.com

 

 

Use the following codes to send email with PHP

 

 

    //  $to  : receiver email address
    //  $subject :  Japanese subject
    //  $message : Japanese body
    function sendEmail($to, $subject, $message)
    {
        if(!isset($to) || !isset($subject) || !isset($message)) {
            return;
        }
   
         // Set up environment
        mb_language('Japanese');
        mb_internal_encoding('UTF-8');
   
        // Set up subject
        $headers ='From: '.mb_encode_mimeheader("ありがとうございます").' <test@123.jp>' . "\r\n";
                'Reply-To: test@123.jp' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion();
   
          // Set up body
        $message = mb_convert_encoding($message, "JIS", "UTF-8");
       
         //  Send email  
        if(mb_send_mail($to, $subject, $message, $headers))
        {
                error_log("#### Send mail OK ####");
   
        }else {
                 error_log("#### Send mail Error ####");
      }
       
    } // End Send Email

 




Create a dropdown Date using JavaScript

1. Include jquery, moment.js and combodate.js on your page
  1. <script src="js/jquery.js"></script>
  2. <script src="js/moment.min.js"></script>
  3. <script src="js/combodate.js"></script>
2. Markup input elements to be used for date and time values
  1. <input name="playerDate" value="15-05-1984" data-format="DD-MM-YYYY" data-template="D MMM YYYY">  
3.Markup Javascript
 <script type="text/javascript">
  // Date 
  $(function(){
   $('#playerDate').combodate();  });
</script> 

 
Download source code: 
https://github.com/gcoolmaneric/jquery-php-html5/tree/master/dropdownDate

 

Upload images using JQuery and PHP for different device

Do you want to create a form that could allow you to upload images on different device ?
You can use jquery and php to make it done.

Add the following codes to html page. 

<body>
     <form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
            <div id="drop">
                Drop Here

                <a>Browse</a>
                <input type="file" name="upl" multiple />
            </div>

            <ul>
                <!-- The file uploads will be shown here -->
            </ul>

        </form>

        <!-- JavaScript Includes -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="assets/js/jquery.knob.js"></script>

        <!-- jQuery File Upload Dependencies -->
        <script src="assets/js/jquery.ui.widget.js"></script>
        <script src="assets/js/jquery.iframe-transport.js"></script>
        <script src="assets/js/jquery.fileupload.js"></script>
       
        <!-- Our main JS file -->
        <script src="assets/js/script.js"></script>
</body>

PHP Code

upload.php
<?php

// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
        echo '{"status":"success"}';
        exit;
    }
}

echo '{"status":"error"}';
exit;

?>

Download source codes:
https://github.com/gcoolmaneric/jquery-php-html5/tree/master/uploadImage


Change the maximum upload file size


You need to set the value of upload_max_filesize and post_max_size in your php.ini :
 vim /etc/php5/apache2/php.ini 
; Maximum allowed size for uploaded files.
upload_max_filesize = 20M

; Must be greater than or equal to upload_max_filesize
post_max_size = 20M