Character encoding to UTF-8

 

header('Content-Type: text/html; charset=utf-8');

ini_set("default_charset", "UTF-8");

mb_internal_encoding("UTF-8");


function clean($string) {

   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

 }


 function clean4($string) {

   //$string = mb_convert_encoding($string, 'UTF-16LE', 'UTF-8');

   //$string = iconv(mb_detect_encoding($string, mb_detect_order(), true), "UTF-8", $string);

   $string = trim(ltrim(ltrim($string,":"),"-"));

   //return preg_replace('/[^A-Za-z0-9\-]/', ' ', trim($string));

   return trim($string);

 }


function isUTF8($string) {

    return (utf8_encode(utf8_decode($string)) == $string);

}

function replace_unicode_escape_sequence($match) {

return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');

}


$string = iconv(mb_detect_encoding($string, mb_detect_order(), true), "UTF-8", $string);


htmlspecialchars_decode(htmlspecialchars(get_the_title($postID), ENT_QUOTES, 'UTF-8'));

Simple Encrypt and Decrypt using PHP and aes-256


  

$key ="<SOME_KEY_HERE>";

$iv='<SOME_KEY_HERE>';


function encryptFile($encKey, $encIV, $instr, $outPath) {

    $sourceFile=$instr;

    $key = base64_decode($encKey);

    $iv = base64_decode($encIV);

    $encrypter = 'aes-256-cbc';

    $encryptedString = openssl_encrypt($sourceFile, $encrypter, $key, 0, $iv);

    return $encryptedString;

}


function decryptFile($encKey, $encIV, $instr, $outPath) {

    $encryptedString=$instr;

    $key = base64_decode($encKey);

    $iv = base64_decode($encIV);

    $encrypter = 'aes-256-cbc';

    $decrypted = openssl_decrypt($encryptedString, $encrypter, $key, 0, $iv);

    return $decrypted;

}


$encstr = encryptFile ($key, $iv,"<TEXT TO ENCRYPT>","");

echo $encstr; //encrypted text here


$Dencstr = decryptFile ($key, $iv,$encstr,"");

echo "<br>";

echo $Dencstr;

Send SMS using Infobip API | PHP | Curl call


Recently I used Infobip SMS gateway for my client. It is Wocommerce website. so we are sending SMS communication for various Wocommerce events.
Hope this sample curl code will help you.

Requirement for SMS send using API.
1) Infobip account and Authentication Key
2) Approved SMS templates
3) Approved DLT
4) Approved Sender Name

PHP Code as follows.

//call a function to send SMS
sendSMSNotification($to, $name, $smsType, $var1, $var2);

function sendSMSNotification($to, $name, $smsType, $var1, $var2){

    $messageId = <UNIQUE_MESSAGE_ID>;
    $notifyUrl = "<NOTIFY_URL>";

    $dltArray = ['DLT_ID_1','DLT_ID_2','DLT_ID_3','DLT_ID_4','DLT_ID_5','DLT_ID_6','DLT_ID_7','DLT_ID_8','DLT_ID_9'];

//List of events for sending SMS communications.
    $smsTypeArray = ['shipped','delivered','feedback','abandonmentcart','cancelled','outfordelivery','orderconfirmed','passwordresetotp','registrationotp'];
    
//List of approved SMS templates
    $msgTemplatesArray = [
    "Hi {$name}. Your order has shipped. Keep track of your delivery here: {$var1}{$var2}",
    "Hi {$name}, Your order from us has been delivered. You can view your order here: {$var1}{$var2}",
    "Hi {$name}, It's been a week since your order was delivered. Would you take one minute to tell us about your experience? You can leave a review here: {$var1}{$var2}",
    "Hi {$name}, You left some items in your cart! We wanted to make sure you had the chance to get what you needed. Shop now: {$var1}{$var2}",
    "Hi {$name}. Heads up - Your order from {$var1} has been cancelled now. Please check status here {$var2}",
    "Hi {$name}. Heads up  - Your order from {$var1} is out for delivery and will arrive soon",
    "Thanks for shopping with us! Your order is confirmed and will be shipped shortly. Check your status here: <WEBSITE_URL>",
    "To reset your password, validate with this OTP, {$var1}. <CLIENT_NAME>",
    "Thank you for registering on <CLIENT_NAME> website. Your OTP is {$var1}. Validate within 15 minutes. Do not share OTP with any one. <WEBSITE_URL>"
    ];

    $key = array_search($smsType,$smsTypeArray);

    $destination = array("messageId" => $messageId, "to" => $to);

    $message = array(
        "from" => '<SENDER_ID>',
        "indiaDltContentTemplateId" => $dltArray[$key],
        "indiaDltPrincipalEntityId" => '<ENTITY_ID_Number>',
        "destinations" => array($destination),
        "text" => $msgTemplatesArray[$key],
        "notifyUrl" => $notifyUrl,
        "notifyContentType" => 'application/json',
        "callbackData" => '');

    $postData = array("messages" => array($message));
    $postDataJson = json_encode($postData);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, '<INFOBIP_BASE_URL>/sms/2/text/advanced');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson);
    $headers = array();
    $headers[] = 'Authorization: App <INFOBIP_KEY>';
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Accept: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
        return 0;
    }
    curl_close($ch);

    //return $result;
    return 1;

}


Send SMS using msg91 API | PHP | Curl call




Msg91 is a my preferred SMS gateway. I used in most of the Apps and websites.

Requirement for SMS send using API.
1) MSG91 account and Authentication Key
2) Approved SMS templates
3) Approved DLT
4) Approved Sender Name

PHP Code as follows.

//below is the post-fields 
//json_string = "{ \"sender\": \"<SENDER_NAME>\", \"route\": \"4\", \"country\": \"91\", \"sms\": [ { \"message\": \"Hi, Your OTP is $num for verification on test.\", \"to\": [ \"$phone\" ] } ] }",

$postDataJson = json_encode($postData);

$authentication_key = "<MSG91_Authntication_Key>";    

//phone number with country code prefix
//here 91 in country code for India
$phone = '910000000000';

$postData = array(
    "sender" => "<SENDER_NAME>", 
    "route" => "4", 
    "country" => "91", 
    "sms" => array(
        "message" => "Hi, Your OTP is {$otp} for verification on {$var2}.",
        "to" => [$phone]
    )
);

$curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.msg91.com/api/v2/sendsms",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $postDataJson,
      CURLOPT_SSL_VERIFYHOST => 0,
      CURLOPT_SSL_VERIFYPEER => 0,
      CURLOPT_HTTPHEADER => array(
        "authkey: $authentication_key",
        "content-type: application/json"
    ),
  ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

Most Useful common Regex collection


The most commonly used and useful regexes collection.

1) Trim trailing spaces
=> ^[\s]*(.*?)[\s]*$

2) Matches any valid HTML tag. (Not for nested tags)
=> <([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)

3) Check for Hexadecimal value
=> \B#(?:[a-fA-F0–9]{6}|[a-fA-F0–9]{3})\b

4) Validate email ID
=> \b[\w.!#$%&’*+\/=?^`{|}~-]+@[\w-]+(?:\.[\w-]+)*\b

5) Username validation
Minimum length of 3, maximum length of 16, composed by letters, numbers or dashes.
=> /^[a-z0-9_-]{3,16}$/

6) Password checking
Moderate password - Minimum length of 6, at least one uppercase letter, at least one lowercase letter, at least one number, at least one special character
=> (?=^.{6,}$)((?=.*\w)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[|!"$%&\/\(\)\?\^\'\\\+\-\*]))^.*

Strong password - Should have 1 lowercase letter, 1 uppercase letter, 1 number, 1 special character and be at least 8 characters long
=> /(?=(.*[0-9]))(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?])(?=.*[a-z])(?=(.*[A-Z]))(?=(.*)).{8,}/

7) URL (http, https or ftp) checking
If you want to use capturing groups to get scheme, path, etc. (or add user-info, host, port…)
=> ^(((https?|ftp):\/\/)?([\w\-\.])+(\.)([\w]){2,4}([\w\/+=%&_\.~?\-]*))*$

8) IPv4 address validation
=> \b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b

9) Alpha-numeric, literals, digits, lowercase, uppercase chars only
\w                //alpha-numeric only
[a-zA-Z]          //literals only
\d                //digits only
[a-z]             //lowercase literal only
[A-Z]             //uppercase literal only

10) find an image with a specific source
enter image name to search img tags with specific image
=> /<img.*src=".*IMAGE-NAME-HERE".*?>/
eg:- preg_replace('/<img.*src=".*'.basename($img_path).'".*?>/', 'REPLACE-WITH', $string);
- here i am replacing image tags where image name matches.

11) find and replace all image tags
=> /<img[^>]+\>/i

12) remove specific html tags
remove any html tag, mention html tag without brackets.
=> /<\\/?HTML-TAG-HERE(.|\\s)*?>/

13) get image source from <img tag>
=> /^<\s*img[^>]+src\s*=\s*(["'])(.*?)\1[^>]*>$/

14) remove junk characters from string
=> '/[^(\x20-\x7F)\x0A\x0D]*/'
eg:- preg_replace('/[^(\x20-\x7F)\x0A\x0D]*/','', $string);

15) remove white spaces from string
=> /\s+/
eg:- preg_replace('/\s+/', '-', $string);
- here i am replacing spaces with '-'

16) remove non-alphanumeric character from string
=> /[^A-Za-z0-9\-]/
eg:- preg_replace('/[^A-Za-z0-9\-]/', '-', $galleryURL)
- here i am replacing any non alphanumeric character with '-'

17) remove a specific attribute from tags.
=> / attribute=("|\')(.*?)("|\')/
eg:- preg_replace('/ style=("|\')(.*?)("|\')/','',$string);
here i am replacing style attribute from html tags.

18) remove <script> tag from string
=> #<script(.*?)>(.*?)</script>#is
eg:- preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string);
- here i am removing script tags from html string

19) replace shortcode (useful for wordpress)
=> /\[SHORTCODE_HERE id="([^"]*)"]/

20) Javascript Handlers
Inline JS handler => /\bon\w+=\S+(?=.*>)/
Inline JS handler with element => /(?:<[^>]+\s)(on\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/

more to coming soon...

Create and Send Campaign Using MooSend API

<?php

$apikey = "<MOOSEND-API-KEY-HERE>";
$listID = "<MOOSEND-LIST-ID-HERE>";
$ep = "https://api.moosend.com/v3/";

$ch = curl_init();

$url = $ep."campaigns/create.json?Format=json&apikey=".$apikey;

$bulkPostFields = array (
  'Name' => '<CAMPAIGN-NAME-HERE>',
  'Subject' => '<CAMPAIGN-SUBJECT-HERE>',
  'SenderEmail' => '<SENDER-EMAIL-ID-HERE>',
  'ReplyToEmail' => '<SENDER-EMAIL-ID-HERE>',
  'ConfirmationToEmail' => '<SENDER-EMAIL-ID-HERE>',
  'MailingLists' => [
array (
'MailingListID' => "<MOOSEND-LIST-ID-HERE>",
'SegmentID' => "<MOOSEND-SEGMENT-ID-HERE>"
),
],
'WebLocation' => "PATH-TO-HTML-EMAILER",
);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($bulkPostFields));
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Accept: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}else{
$res = json_decode($result);
$campaignID = $res->Context;
}
curl_close ($ch);

//campaign send here
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $ep."campaigns/".$campaignID."/send.json?apikey=".$apikey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Accept: application/json";
$headers[] = "Content-Length: 0";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}else{
echo $result;
}
curl_close ($ch);

?> 

Create and Send Campaign Using Active Campaign API


Coming Soon..

Create and Send Campaign Using SendGrid API

<?php

$apiKey = "<SENDGRID-API-KEY-HERE>";
     
        $html_content = file_get_contents($emailerpath);
        $html_content = str_replace("*|UNSUB|*", "[unsubscribe]", $html_content); //code to add unsubscribe link

        $titleText = 'AD Daily - ' . date("Y-m-d");
        $postFields = array('title' => '<CAMPAIGN-NAME-HERE>', 'subject' => '<CAMPAIGN-SUBJECT-HERE>', "sender_id" => "<SENDER-ID-HERE>",
            "list_ids" => array("<LIST-ID-HERE>"),
            "categories" => array("<CAMPAIGN-CATEGORY>"),
            "html_content" => $html_content,
            "plain_content" => $mail_subject . ' <a href="[unsubscribe]" style="text-decoration:none;" target="_blank"><span style="color: #000000;">Unsubscribe</span></a>',
            "suppression_group_id" => "<UNSUBSCRIBE-GROUP-ID-HERE>",
        );
        $aa = json_encode($postFields);

        //create a campaign using sendGrid
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.sendgrid.com/v3/campaigns",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $aa,
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer " . $apiKey . "",
                "content-type: application/json"
            ),
        ));
        $response = json_decode(curl_exec($curl));
        $err = curl_error($curl);
        curl_close($curl);
     
        if ($err) {
            echo "<br/>cURL Error #:" . $err;
        } else {
            $campaignID = $response->id;
        }

//send a campaign using sendGrid
        if (isset($campaignID) && $campaignID != "") {
            echo " campaignID ==> " . $campaignID;
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://api.sendgrid.com/v3/campaigns/" . $campaignID . "/schedules/now",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => "null",
                CURLOPT_HTTPHEADER => array(
                    "authorization: Bearer " . $apiKey . "",
                    "content-type: application/json"
                ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
                echo "<br/>cURL Error #:" . $err;
            } else {
                echo '<br/>Operation completed without any errors <br/>';
                echo $response;
            }
        }

?>

Create and Send Campaign Using Mailchimp API


<?php

//Include MailChimp API version 3 Class Library
include('mcv3/src/MailChimp.php');

use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp('<MAILCHIMP-API-KEY-HERE>');

//create campaign at Mailchimp
$result = $MailChimp->post('campaigns', array(
            "type" => 'regular',
            "recipients" => array(
                "list_id" => "<LIST-ID-HERE>",
                "segment_opts" => array(
                    "match" => "any",
                    "conditions" => array(
                        array("field" => "interests-<INTEREST-GROUP-ID-HERE>", "op" => "interestcontains", "value" => ["<INTEREST-ID-HERE>"])
                    ),
                )
            ),
            'settings' => array(
                'subject_line' => '<CAMPAIGN-SUBJECT-HERE>',
                'title' => '<CAMPAIGN-NAME-HERE>',
                'from_name' => '<FROM-NAME-HERE>',
                'reply_to' => '<FROM-EMAIL-ID-HERE>',
                'auto_footer' => false
            ),
            'content' => array('url' => $emailerpath),
        ));
        $campaign_id = $result['id'];

        //sleep for Sometime
        sleep(20);

//put content to campaign
        $contentx = json_encode($MailChimp->put('/campaigns/' . $campaign_id . '/content', array('url' => $emailerpath)
        ));

        //sleep for Sometime
        sleep(20);

//send email to list
        echo json_encode($MailChimp->post('/campaigns/' . $campaign_id . '/actions/send'));

?>

Remove empty items from a multidimensional array in PHP



The following function removes empty items from a (multidimensional) array and returns the resulting array. Please notice that the use of recursion is required because of the array can be of an unknown number of levels, that is, arrays inside the cells of the array, and so on.

function array_non_empty_items($input) {
    // If it is an element, then just return it
    if (!is_array($input)) {
      return $input;
    }
    $non_empty_items = array();
    foreach ($input as $key => $value) {
      // Ignore empty cells
      if($value) {
        // Use recursion to evaluate cells 
        $non_empty_items[$key] = array_non_empty_items($value);
      }
    }
    // Finally return the array without empty items
    return $non_empty_items;
  }


By example, if we pass the following array to the function:

  $MasterArray = array(
      ‘country’ => ‘CO’,
      ‘region’ => ”,
      ‘city’ => ”,
      ‘features’ => array(
          ‘home’ => array(‘garden’, ‘bedrooms’=>3),
          ‘beach’ => array(‘no_more_than’=>30, ‘yachts_rental’),
          ‘supermarkets’ => ”,
          ‘discotheque’ => ”
       )
    );

Then we will obtain an array without empty items, like this:

$MasterArray = array(
    ‘country’ => ‘CO’,
    ‘ features’ => array(
    ‘home’ => array(‘garden’, ‘ bedrooms’=>3),
    ‘ beach’ => array(‘no_more_than’=>30, ‘ yachts_rental’)
 )
);









HTML Share Buttons


These simple social Share Button Codes will help you alot.

<div id="share-buttons">
 
    <!-- Buffer -->
    <a href="https://bufferapp.com/add?url=https://sourcecode-kk.blogspot.in&amp;text=Simple Share Buttons" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/buffer.png" alt="Buffer" />
    </a>
 
    <!-- Digg -->
    <a href="http://www.digg.com/submit?url=https://sourcecode-kk.blogspot.in" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/diggit.png" alt="Digg" />
    </a>
 
    <!-- Email -->
    <a href="mailto:?Subject=Simple Share Buttons&amp;Body=I%20saw%20this%20and%20thought%20of%20you!%20 https://sourcecode-kk.blogspot.in">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/email.png" alt="Email" />
    </a>

    <!-- Facebook -->
    <a href="http://www.facebook.com/sharer.php?u=https://sourcecode-kk.blogspot.in" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/facebook.png" alt="Facebook" />
    </a>
 
    <!-- Google+ -->
    <a href="https://plus.google.com/share?url=https://sourcecode-kk.blogspot.in" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/google.png" alt="Google" />
    </a>
 
    <!-- LinkedIn -->
    <a href="http://www.linkedin.com/shareArticle?mini=true&amp;url=https://sourcecode-kk.blogspot.in" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/linkedin.png" alt="LinkedIn" />
    </a>
 
    <!-- Pinterest -->
    <a href="javascript:void((function()%7Bvar%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)%7D)());">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/pinterest.png" alt="Pinterest" />
    </a>
 
    <!-- Print -->
    <a href="javascript:;" onclick="window.print()">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/print.png" alt="Print" />
    </a>
 
    <!-- Reddit -->
    <a href="http://reddit.com/submit?url=https://sourcecode-kk.blogspot.in&amp;title=Simple Share Buttons" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/reddit.png" alt="Reddit" />
    </a>
 
    <!-- StumbleUpon-->
    <a href="http://www.stumbleupon.com/submit?url=https://sourcecode-kk.blogspot.in&amp;title=Simple Share Buttons" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/stumbleupon.png" alt="StumbleUpon" />
    </a>
 
    <!-- Tumblr-->
    <a href="http://www.tumblr.com/share/link?url=https://sourcecode-kk.blogspot.in&amp;title=Simple Share Buttons" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/tumblr.png" alt="Tumblr" />
    </a>
   
    <!-- Twitter -->
    <a href="https://twitter.com/share?url=https://sourcecode-kk.blogspot.in&amp;text=Simple%20Share%20Buttons&amp;hashtags=sourcecode-kk" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/twitter.png" alt="Twitter" />
    </a>
 
    <!-- VK -->
    <a href="http://vkontakte.ru/share.php?url=https://sourcecode-kk.blogspot.in" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/vk.png" alt="VK" />
    </a>
 
    <!-- Yummly -->
    <a href="http://www.yummly.com/urb/verify?url=https://sourcecode-kk.blogspot.in&amp;title=Simple Share Buttons" target="_blank">
        <img src="http://sourcecode-kk.blogspot.inimages/somacro/yummly.png" alt="Yummly" />
    </a>

</div>

Social Meta Tags for Twitter, Google+, Facebook and More



Knowing exactly which social meta tags to include can be confusing even to experienced webmasters. This post is a huge help, and Wordpress publishers who use Yoast's SEO plugin are well ahead of the game. For the rest of us, consider the different structures supported by the major social platforms:
  1. Twitter Cards: Summaries, Images, Galleries, Apps, Video, Audio, and Products
  2. Pinterest Rich Pins: Products, Recipes, Movies, and Articles
  3. Google+: Articles, Blog, Book, Event, Local Business, Organization, Person, Product, and Reviews
  4. Facebook: Articles, Photos, Audio, Video, and more

How to use these templates

1. The Minimal Template

This slimmed back version runs lean and fast. It contains a bare minimum of data for optimized sharing across Twitter, Facebook, Google+ and Pinterest.

<!-- Place this data between the <head> tags of your website -->
<title>Page Title. Maximum length 60-70 characters</title>
<meta name="description" content="Page description. No longer than 155 characters." />
<!-- Twitter Card data -->
<meta name="twitter:card" value="summary">
<!-- Open Graph data -->
<meta property="og:title" content="Title Here" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.example.com/" />
<meta property="og:image" content="http://example.com/image.jpg" />
<meta property="og:description" content="Description Here" />

2: The Standard Template

The standard template represents a more robust implementation of social tags and is meant to work across all platforms. In addition to all of the features of the mimimal template above, the standard template includes the following:

  • The basic Twitter Summary card
  • Twitter thumbnail image
  • Facebook Page Insights

<!-- Place this data between the <head> tags of your website -->
<title>Page Title. Maximum length 60-70 characters</title>
<meta name="description" content="Page description. No longer than 155 characters." />

<!-- Twitter Card data -->
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@publisher_handle">
<meta name="twitter:title" content="Page Title">
<meta name="twitter:description" content="Page description less than 200 characters">
<meta name="twitter:creator" content="@author_handle">
<-- Twitter Summary card images must be at least 120x120px -->
<meta name="twitter:image" content="http://www.example.com/image.jpg">

<!-- Open Graph data -->
<meta property="og:title" content="Title Here" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.example.com/" />
<meta property="og:image" content="http://example.com/image.jpg" />
<meta property="og:description" content="Description Here" /> 
<meta property="og:site_name" content="Site Name, i.e. Moz" />
<meta property="fb:admins" content="Facebook numeric ID" />

3: The Full Script

In addition to all the data contained in the standard template, the full template contains:
  • Google Authorship and Publisher Markup. Although this data doesn't change your content appearance in Google+, it potentially add links to your Google+ pages in search results.
  • Schema.org article markup
  • Twitter Summary card with large image
  • Expanded Open Graph article data
<!-- Update your html tag to include the itemscope and itemtype attributes. -->
<html itemscope itemtype="http://schema.org/Article">

<!-- Place this data between the <head> tags of your website -->
<title>Page Title. Maximum length 60-70 characters</title>
<meta name="description" content="Page description. No longer than 155 characters." />

<!-- Schema.org markup for Google+ -->
<meta itemprop="name" content="The Name or Title Here">
<meta itemprop="description" content="This is the page description">
<meta itemprop="image" content="http://www.example.com/image.jpg">

<!-- Twitter Card data -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@publisher_handle">
<meta name="twitter:title" content="Page Title">
<meta name="twitter:description" content="Page description less than 200 characters">
<meta name="twitter:creator" content="@author_handle">
<!-- Twitter summary card with large image must be at least 280x150px -->
<meta name="twitter:image:src" content="http://www.example.com/image.jpg">

<!-- Open Graph data -->
<meta property="og:title" content="Title Here" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.example.com/" />
<meta property="og:image" content="http://example.com/image.jpg" />
<meta property="og:description" content="Description Here" />
<meta property="og:site_name" content="Site Name, i.e. Moz" />
<meta property="article:published_time" content="2013-09-17T05:59:00+01:00" />
<meta property="article:modified_time" content="2013-09-16T19:08:47+01:00" />
<meta property="article:section" content="Article Section" />
<meta property="article:tag" content="Article Tag" />
<meta property="fb:admins" content="Facebook numberic ID" />

4. Bonus: The Product Template

For merchants, product markup is very popular, and usually easy for developers to implement in their shopping cart software. The product template differs from article markup in only a few ways:

  • Modified <html> tag to reflect schema.org product data
  • Twitter Product Card includes required data labels
  • Open Graph data includes price and currency data
<!-- Update your html tag to include the itemscope and itemtype attributes. -->
<html itemscope itemtype="http://schema.org/Product">

<!-- Place this data between the <head> tags of your website -->
<title>Page Title. Maximum length 60-70 characters</title>
<meta name="description" content="Page description. No longer than 155 characters." />

<!-- Schema.org markup for Google+ -->
<meta itemprop="name" content="The Name or Title Here">
<meta itemprop="description" content="This is the page description">
<meta itemprop="image" content="http://www.example.com/image.jpg">

<!-- Twitter Card data -->
<meta name="twitter:card" content="product">
<meta name="twitter:site" content="@publisher_handle">
<meta name="twitter:title" content="Page Title">
<meta name="twitter:description" content="Page description less than 200 characters">
<meta name="twitter:creator" content="@author_handle">
<meta name="twitter:image" content="http://www.example.com/image.jpg">
<meta name="twitter:data1" content="$3">
<meta name="twitter:label1" content="Price">
<meta name="twitter:data2" content="Black">
<meta name="twitter:label2" content="Color">

<!-- Open Graph data -->
<meta property="og:title" content="Title Here" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.example.com/" />
<meta property="og:image" content="http://example.com/image.jpg" />
<meta property="og:description" content="Description Here" />
<meta property="og:site_name" content="Site Name, i.e. Moz" />
<meta property="og:price:amount" content="15.00" />
<meta property="og:price:currency" content="USD" />

Use these templates as a starting point, but you can customize them in millions of ways.

permalink problem for wordpress site on iis



<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
    <rules>
        <rule name="Main Rule" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="index.php" />
        </rule>
    </rules>
</rewrite>
</system.webServer>
</configuration>

Social Follower Count using PHP

This post will help you to find snippets to get followers count for social platforms like Facebook, Twitter, Google plus,  Youtube, Instagram, Pinterest  and Tumblr.

Facebook Followers Count
$FBFollowercount = file_get_contents('http://api.facebook.com/method/fql.query?format=json&query=select+fan_count+from+page+where+page_id%3D355692061120689');
$data = json_decode($FBFollow);
echo $data[0]->fan_count;

Twitter followers Count
require_once 'twitteroauth.php';
define("CONSUMER_KEY", "****consumer key*******");
define("CONSUMER_SECRET", "*******Consumer secret********");
define("OAUTH_TOKEN", "**********Oauth token*******");
define("OAUTH_SECRET", "*****Oauth Secret********");
$username = 'Walkswithmenet'; //Your twitter screen name or page name
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$followers = $connection->get('https://api.twitter.com/1.1/users/show.json?screen_name='.$username);
echo ($followers->followers_count);

Google Plus Followers Count
/ get api https://code.google.com/apis/console?hl=en#access
$google_api_key = 'YOUR_API';
$page_id = 'YOUR_PAGE_ID';
$data = @file_get_contents("https://www.googleapis.com/plus/v1/people/$page_id?key=$google_api_key");
$data = json_decode($data, true);
echo $data['plusOneCount'];

Youtube Subscribers
$channel_name = 'Your Channel';
$data = file_get_contents("http://gdata.youtube.com/feeds/api/users/$channel_name?alt=json");
$data = json_decode($data, true);
$subscribersDetails = $data['entry']['yt$statistics'];
echo $subscribersDetails['subscriberCount'].'<br />';
echo $subscribersDetails['viewCount'].'<br />';

Instagram Followers
Register the app you will get an API Key and secret.
$api_key = 'API_KEY';
$user_id = 'UID';
$data = @file_get_contents("https://api.instagram.com/v1/users/$user_id/?client_id=$api_key");
$data = json_decode($data, true);
echo '<pre/>';
print_r($data);
echo $data['data']['counts']['followed_by'];

Pinterest Followers Count
$metas = get_meta_tags('http://pinterest.com/YOUR PINTREST ACCOUNT NAME/');
print_r($metas['pinterestapp:followers']);

Tumblr Likes
Login to Tumblr -> Setting Menu -> APP ->Register your APP get the API Key and secret key.
$api_key = 'API_KEY';
$blog_name = 'Blog_name';
$data = @file_get_contents("http://api.tumblr.com/v2/blog/$blog_name/info?api_key=$api_key");
$data = json_decode($data, true);
echo '<pre/>';
print_r($data);
echo $data['response']['blog']['likes'];


Custom Social Share Buttons



Now a days social media is important part of web development and brand promotions. Social share buttons are widely used things on a web site, while developing each site we concentrate how we can use all buttons,icons images are very close to the template.

This article will help to create custom social share buttons for Facebook, Google Plus, Pinterest, Tumblr , Twitter and Linked In.

For Facebook share button.
<a id="ref_fb"  href="http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $description;?>&amp;p[url]=<?php echo urlencode($share_url);?>&amp;
p[images][0]=<?php echo $image_url;?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600'); return false;"><img src="your custom facebook share button image" alt=""/></a>

Twitter Share Button
<a id="ref_tw" href="http://twitter.com/home?status=<?php echo $title; ?>+<?php echo urlencode($share_url);?>"  onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false;"><img src="your custom twitter share button image" alt=""/></a>

Google Plus share button
<a id="ref_gp" href="https://plus.google.com/share?url=<?php echo urlencode($share_url);?>"
onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false"><img src="your custom gplus share button image" alt=""/></a>

Pinterest share button.
<a id="ref_pr" href="http://pinterest.com/pin/create/bookmarklet/?media=<?php echo urlencode($share_image);?>&amp;
url=<?php echo urlencode($share_url);?>&amp;
is_video=false&amp;description=<?php echo $description;?>"
onclick="javascript:window.open(this.href, '_blank', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false;"><img src="your custom pin share button image" alt=""/></a>

Linked In share button.
<a id="ref_lkd" href="http://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode($share_url);?>&title=<?php echo strip_tags($title); ?>&source=<?php echo urlencode($siteurl);?>"
onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false;"><img src="your custom pin share button image" alt=""/></a>

Tumblr share button.
<a id="ref_tum" href="http://www.tumblr.com/share/photo?source=<?php echo urlencode($share_image);?>&amp;caption=<?php echo $description;?>&amp;clickthru=<?php echo urlencode($share_url);?>"
onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false;"><img src="your custom pin share button image" alt=""/></a>

Dynamically reate Social share buttons
var share_url         =    "your url to share" ;
var share_image      =    "your image to share";
//full url not ../images should be http://www.
var title               =    "title";
var description       =    "description";
//title and description should be formatted ie, remove all special char otherwise it may creates errors on social media sites.
var FB_url             =    "http://www.facebook.com/sharer.php?s=100&p[title]="+(title)+"&p[summary]="+description+"&p[url]="+encodeURIComponent(share_url)+"&p[images][0]="+(share_image);
var GP_url            =    "https://plus.google.com/share?url="+encodeURIComponent(share_url);
var TW_url            =    "http://twitter.com/home?status="+escape(title)+"+"+encodeURIComponent(share_url);
var Pt_url            =    "http://pinterest.com/pin/create/bookmarklet/?media="+encodeURIComponent(share_image)+"&url="+encodeURIComponent(share_url)+"& is_video=false&description="+description;
var TB_url            =    "http://www.tumblr.com/share/photo?source="+encodeURIComponent(share_image)+"&caption="+(description)+"&clickthru="+encodeURIComponent(share_url);
var LK_url            =    "http://www.linkedin.com/shareArticle?mini=true&url="+encodeURIComponent(share_url)+"&title="+(title)+"&source="+encodeURIComponent(siteurl);
jQuery("#ref_fb").attr('href',FB_url);
jQuery("#ref_gp").attr('href',GP_url);
jQuery("#ref_tw").attr('href',TW_url);
jQuery("#ref_pr").attr('href',Pt_url);
jQuery("#ref_tum").attr('href',TB_url);
jQuery("#ref_lkd").attr('href',LK_url);

Note: please make sure to add jquery library in page.

get utm paramater from url in javascript



UTM paramaters are widely used in adcampaigns to check sources are traffice. google ads and other ads send a parameters, such as utm_source, utm_medium, utm_campaign in urls.

Some of the utm paramaters are as follows:-
1) Campaign Source (utm_source) – Required parameter to identify the source of your traffic such as: search engine, newsletter, or other referral.
2) Campaign Medium (utm_medium) – Required parameter to identify the medium the link was used upon such as: email, CPC, or other method of sharing.
3) Campaign Term (utm_term) – Optional parameter suggested for paid search to identify keywords for your ad. You can skip this for Google AdWords if you have connected your AdWords and Analytics accounts and use the auto-tagging feature instead.
4) Campaign Content (utm_content) – Optional parameter for additional details for A/B testing and content-targeted ads.
5) Campaign Name (utm_campaign) – Required parameter to identify a specific product promotion or strategic campaign such as a spring sale or other promotion.

Simple code snippet to get get url paramater values for utm sources.

//function to get url paramaters
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

//variable to stor url values
var utmsource = getUrlVars()["utm_source"];
var utm_medium = getUrlVars()["utm_medium"];
var utm_campaign = getUrlVars()["utm_campaign"];

Similarly you can get all other valiables from url.

Mobile First Media Queries for Resposive sites



Today we will look into media queries. Many peoples are searching for media queries format on google, but many times they dont get proper solution . so i am sharing Media query structure which i follow while writing css. hope this will be useful for all of you.

A media query consists of a media type and at least one expression that limits the style sheets' scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.

Which direction should you choose when writing the CSS for a responsive website?

1) Mobile First :-
Start with the CSS for narrow viewports , then increase viewport and add breakpoints when needed.

2) Desktop First :-
Start with the CSS for wider viewports , then decrease viewport and add breakpoints when needed.

Mobile First Structure is as follows

/*==========  Mobile First Method  ==========*/

/* Custom, iPhone Retina */
@media only screen and (min-width : 320px){
      /* Some CSS Here */
}

/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px){
      /* Some CSS Here */
}

/* Small Devices, Tablets */
@media only screen and (min-width : 768px){
      /* Some CSS Here */
}

/* Medium Devices, Desktops */
@media only screen and (min-width : 992px){
      /* Some CSS Here */
}

/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px){
      /* Some CSS Here */
}

All the best........


URL Rewriting using .htaccess in PHP



Benefits of Static url over Dynamic URLs
1. Static URLs typically Rank better in Search Engines.
2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages.
3. Static URLs are always more friendlier looking to the End Users.

What is the benefits of rewriting URL?
When a search engine visits the dynamic url like product.php?id=3 it does not give much importance to that URL as search engine sees ? sign treat it as a url which keeps on changing. so we are converting the dynamic URL like the product.php?id=3 to static url format like product-3.html. We rewrite the url in such a way that in browser's address bar it will display as a product-3.html but it actually calls the file product.php?id=3. So that why these kind of URL also named as SEO friendly URL.

What is required for URL rewriting ??
To rewrite the URL you must have the mod_rewrite module must be loaded in apache server. And furthermore, FollowSymLinks options also need to be enabled otherwise you may encounter 500 Internal Sever Error.

If you are looking for the examples of URL rewriting then this post might be useful for you. In this post, I've given five useful examples of URL rewriting using .htacess.

Examples of url rewriting for seo friendly URL
For rewriting the URL, you should create a .htaccess file in the root folder of your web directory. And have to put the following codes as your requirement.

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [nc]
The following example will rewrite the test.php to test.html i.e when a URL like http://localhost/test.htm is called in address bar it calls the file test.php. As you can see the regular expression in first part of the RewriteRule command and $1 represents the first regular expression of the part of the RewriteRule and [nc] means not case sensitive.

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ products.php?id=$1
The following example will rewrite the product.php?id=5 to porduct-5.html i.e when a URL like http://localhost/product-5.html calls product.php?id=5 automatically.

SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.

RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
If you like to do like http://yoursite.com/xyz to http://yoursite.com/user.php?username=xyz then you can add the following code to the .htaccess file.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
Suppose the you've redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “test.com/new”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, www.test.com point out to the files inside “new” folder.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

Hope this post will be helpful as other posts.

Parameter passing to CURL GET Request



This is simple example to pass parameters to php curl get method

<?php

    /* Script URL */
    $url = 'http://www.example.com/abc.php';

    /* $_GET Parameters to Send */
    $params = array('param1' => 'value1', 'param2' => 'value2');

    /* Update URL to container Query String of Paramaters */
    $url .= '?' . http_build_query($params);

    /* cURL Resource */
    $ch = curl_init();

    /* Set URL */
    curl_setopt($ch, CURLOPT_URL, $url);

    /* Tell cURL to return the output */
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    /* Tell cURL NOT to return the headers */
    curl_setopt($ch, CURLOPT_HEADER, false);

    /* Execute cURL, Return Data */
    $data = curl_exec($ch);

    /* Check HTTP Code */
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    /* Close cURL Resource */
    curl_close($ch);

    /* 200 Response! */
    if ($status == 200) {

        /* Debug */
        var_dump($data);

    } else {

        /* Debug */
        var_dump($data);
        var_dump($status);

    }

?>

Black Beauties for Techies

Today I am listing some of the black beauties of tech world. which every techies dream to buy. For me Black is a color of new technology and gadgets. Every year the Black Friday online circulars hit the Web and lots of sites round up every tech deal under the sun. Some of the big giants like Apple and Amazon comes with lots of offers on "Black Friday shopping event".

Following are Some of Gadgets actually worth getting excited.


1) iPhone 5s


1) iPhone 5s is the first 64‑bit smartphone in the world. And iOS 7 was designed with that in mind, built specifically for 64‑bit architecture.
2) Beautiful industrial design and superb build quality is matched with a phone that feels almost impossibly thin and light.
3) This is the fingerprint scanner that sits under the surface of the Home button. 
4) 4-inch IPS 1,136 x 640 pixel screen
5) iOS 7 was the biggest update to the system since its birth back in 2007.  It made the OS look and feel more modern, with a new design and better-looking screen transitions.
6) 64-bit dual-core 1.3GHz Apple A7, 1GB RAM, PowerVR G6430 GPU
7) 8-megapixel camera, 1/3.2-inch sensor, dual-LED ‘true tone’ flash

2) Apple iPad mini 2 Retina

1) The 7.9 inch IPS display. 2,048 x 1,536 pixels with a stunning 324 pixels per inch (ppi)
2) 64-bit A7 system-on-chip processor and 1GB RAM
3) Come with IOS 7
4) 5MP rear camera5) bigger battery, from 16.3 Wh to 23.8 Wh



3) MacBook Pro


1) OS X Mavericks. The world's most advanced desktop operating system.
2) Thin. Light. Powerful. There’s innovation in every nanometre.
3) With fourth-generation dual-core and quad-core Intel processors
4) Every new MacBook Pro comes with better-than-ever versions of iPhoto, iMovie, GarageBand, Pages, Numbers and Keynote.
5) the latest graphics, PCIe-based flash storage, 802.11ac Wi‑Fi


4) Nikon D5300 DSLR Camera


1) 24.2-megapixel DX-format CMOS sensor with the optical low pass filter (OLPF) removed to improve clarity and detail in images
2) 3.2-inch vari-angle LCD screen
3) capable of capturing images at a 5fps rate
4) built-in Wi-Fi, the Nikon D5300 can transmit images and videos to any iOS and Android smartphone or tablet
5) GPS function, images can also be geotagged


5) Xbox One with Kinect 2.0



1) Advanced motion sensor
2) Voice commands
3) come with a full 1080p RBG camera for HD detection that may help with facial recognition
4) Xbox One takes on set top TV boxes
5) Multitasking
6) HDMI-IN PORT


6) Programming Black Book collection




This is Specially For Computer Programmers. Black books is a awesome book series from DreamTech Publication. This books are solid introduction, written from the programmer s point of view that contains hundreds of examples covering every aspect of programming languages.
Some of the Black books are as Follows.
i) Java 6 Programming Black Book
ii) C, C++, C# Programming
iii) Java Server Programming JAVA EE 7
Read more: - http://www.dreamtechpress.com/

Hope you will like this post. Please Comment Your Suggestions to improve this blog contents.
Thank You.