Facebook

Tuesday, March 1, 2016

Custom javascript functions

Custom share buttons with javascript - Facebook, Twitter, Pinterest
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<a class="fb-share" href="http://www.facebook.com/sharer/sharer.php?u=http://url/to/your/page"><i class="fa fa-facebook"></i></a>

<a class="tw-share" href="http://twitter.com/intent/tweet?status=custom-title-you-want-to-share+http://url/to/your/page"><i class="fa fa-twitter"></i></a>

<a id="pinterest_share" href="#"><i class="fa fa-pinterest"></i></a>

<div class="hidden" id="pinterest_wrap">
    <a href="https://www.pinterest.com/pin/create/button/" >
        <img src="//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png" />
    </a>
</div>
<script>
$(function () {
    $('#pinterest_share').click(function(){
        $('#pinterest_wrap').find('span').trigger('click');
    })
   $('.fb-share').click(function (e) {
        window.open($(this).attr('href'), 'Share on facebook', 'height=450, width=550, top=' + ($(window).height() / 2 - 275) + ', left=' + ($(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
        return false;
    });
    $('.tw-share').click(function (e) {
        window.open($(this).attr('href'), 'Share on twitter', 'height=450, width=550, top=' + ($(window).height() / 2 - 275) + ', left=' + ($(window).width() / 2 - 225) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
        return false;
    });
});
</script>
<style>. hidden{display:none;}</style>
DEMO:


Fetch / Embed instagram images in your website

Fetch / Embed instagram images in your website
  1. Create a client and get client id
    Go to following url and click on 'Register a new client' on top
    https://www.instagram.com/developer/clients/manage/
    Fill in the form

    Don't forget to enable implicit authentication
  2. Retrieve your access token
    Go to https://instagram.com/oauth/authorize/?client_id=YOURCLIENTIDHERE&amp;redirect_uri=HTTP://YOURREDIRECTURLHERE.COM&amp;response_type=token
    You will be redirected to HTTP://YOURREDIRECTURLHERE.COM#access_token=XXXX
    Copy the access token from url
  3. Find user id corresponding to client
    Your access code will be of following structure
    userid.somethingelse.somethingelse
    First portion of your access token will be your user id
  4. Insert following javascript code
$(document).ready(function() {
    var clientid = $('#INSTAGRAM_CLIENT_ID').val(); // learn how to obtain it below
    var num_photos = 8; // how much photos do you want to get
    var acces_token = $('#INSTAGRAM_ACCESS_TOKEN').val();
    var userid = $('#INSTAGRAM_USER_ID').val();//'2214764568';
    if (clientid != '' && acces_token != '' && userid != '') {
        $.ajax({
            url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent?access_token=' + acces_token,
            dataType: 'jsonp',
            type: 'GET',
            data: {client_id: clientid, count: num_photos},
            success: function (data) {
                console.log(data);
                for (x in data.data) {
                    $('ul#footer_insta').append('<li><a href="' + data.data[x].link + '" target="_blank"><img src="' + data.data[x].images.low_resolution.url + '"></a></li>'); // data.data[x].images.low_resolution.url - URL of image, 306Ñ…306
                }
            },
            error: function (data) {
                console.log(data); // send the error notifications to console
            }
        });
    } else {
        alert("here");
    }
})


Replace 'INSTAGRAM_ACCESS_TOKEN', 'INSTAGRAM_CLIENT_ID', 'INSTAGRAM_USER_ID' with corresponding value.

<input type="hidden" id="INSTAGRAM_ACCESS_TOKEN" value="INSTAGRAM_ACCESS_TOKEN" />
<input type="hidden" id="INSTAGRAM_CLIENT_ID" value="INSTAGRAM_CLIENT_ID" />
<input type="hidden" id="INSTAGRAM_USER_ID" value="INSTAGRAM_USER_ID" />


<ul id="footer_insta"></ul>

Sunday, January 31, 2016


Web config file - alternative of htaccess in windows machine
<?xml version="1.0" encoding="UTF-8"?> <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Clean URL" stopProcessing="true">

                <match url="^news/(.*).html" />
                <action type="Rewrite" url="/newssingle.php?url={R:1}" appendQueryString="true" />

                </rule>
                <rule name="Clean URL 1" stopProcessing="true">

                <match url="^index.html" />
                <action type="Rewrite" url="index.php" appendQueryString="true" />

                </rule>
                <rule name="Clean URL 2" stopProcessing="true">

                <match url="^newsevents.html" />
                <action type="Rewrite" url="newsevents.php" appendQueryString="true" />

                </rule>
                <rule name="Clean URL 3" stopProcessing="true">

                <match url="^contactus.html" />
                <action type="Rewrite" url="contactus.php" appendQueryString="true" />

                </rule>
                <rule name="Clean URL 4" stopProcessing="true">

                <match url="^services.html" />
                <action type="Rewrite" url="services.php" appendQueryString="true" />

                </rule>
                <rule name="Clean URL 5" stopProcessing="true">

                <match url="^aboutus.html" />
                <action type="Rewrite" url="aboutus.php" appendQueryString="true" />

                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Clean URL" stopProcessing="true">
                    <match url="^(.*).html" />
                    <action type="Rewrite" url="/pages.php?page_slug={R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Wednesday, January 6, 2016

Responsive design: Tips and tricks


1. Usage: Make colorbox responsive.

$(document).ready(function() {
    $(".ajax-popup").colorbox({width: "90%",maxWidth: "900px", maxHeight:'90%'});
})

1. Usage: JQuery ui date picker limit date range.

$(document).ready(function() {
    $( "#datePicker" ).datepicker({
        maxDate: "+1M +10D -15Y",
        minDate: -20
    })
})

Saturday, January 2, 2016

Function to render text as image - escape spam bots


Escaping contact information from spam bots is one of the major challenges developers facing. Converting the text to image and rendering as image is one basic solution. Here is a function I use.
Function to render text as image
<img src="<?php echo render_text_image('test image', 183, 50);?>" />


function render_text_image($string, $width, $height, $text_align_pos = 0)
{


    $img = imagecreatetruecolor($width, $height);

    $imageX = imagesx($img);
    $imageY = imagesy($img);

    imagealphablending($img, false);
    imagesavealpha($img, true);

    $transparent = imagecolorallocatealpha($img, 255,255,255, 127);
    $white = imagecolorallocate($img, 129, 78, 16);
    $black = imagecolorallocate($img, 0, 0, 0);
    $grey = imagecolorallocate($img, 127,127,127);
    //imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
    imagefilledrectangle($img, 0, 0, $imageX, $imageY, $transparent);

    $font = ROOT_DIRECTORY . "assets/font/arialbd.ttf";
    //$font = ROOT_DIRECTORY . "assets/font/arialbd.ttf";
    $fontSize = 12;
    $text = $string;

    $textDim = imagettfbbox($fontSize, 0, $font, $text);
    $textX = $textDim[2] - $textDim[0];
    $textY = $textDim[7] - $textDim[1];

    $text_posX = ($text_align_pos== "center") ? ($imageX / 2) - ($textX / 2) : $text_align_pos;
    $text_posY = ($imageY / 2) - ($textY / 2);

    imagealphablending($img, true);
    imagettftext($img, $fontSize, 0, $text_posX, $text_posY, $white, $font, $text);
    //ImageString($img,2,0,0, $text,$black);
    //Get image to a variable
    ob_start();
    imagepng($img);
    // Capture the output
    $imagedata = ob_get_contents();
    // Clear the output buffer
    ob_end_clean();

    return "data:image/png;base64," . base64_encode($imagedata);
}

Monday, December 28, 2015

Function to generate clean url slugs from string with duplication check


Function to generate clean url slugs from string with duplication check


function generateClassifiedSlug($string, $id=0){
    //Set char set to UTF-8 - to manage accented characters
    setlocale(LC_ALL, "en_US.UTF8");
    //Remove everything except alphabets and digits
    $url_string=preg_replace("/[^a-z0-9]/i"," ", ltrim(rtrim(strtolower($string))));
    //Remove multiple spaces
    $url_string = preg_replace("/\s+/", " ", $url_string);
    //Replace space with dashes
    $newurl_string=str_replace(" ","-",$url_string);
    //Condition for add / update
    if(!empty($id) && $id!=0){
        $condition = "BlogId!='".$id."' AND ";
    }else{
        $condition ="";
    }
    $queryCount = 'SELECT blog_url from tblblogs WHERE '.$condition.'
                    blog_url LIKE "'.$newurl_string.'"';

    //Check duplicate
    $rqC = mysql_num_rows(mysql_query($queryCount));
    $i=0;
    while($rqC != 0) {
        $i++;
        //Add number to avoid duplicate
        $newurl_string = $newurl_string."-".$i;
        $queryCount = 'SELECT blog_url from tblblogs WHERE '.$condition.'
                    blog_url LIKE "'.$newurl_string.'-'.$i.'"';
        $rqC = mysql_num_rows(mysql_query($queryCount));
    }

    $newurl_string = $newurl_string.(!empty($i) ? "-".$i : "");

    return $newurl_string;
}

Sunday, December 6, 2015

php file upload: clean name of uploaded file, check for duplicate


File upload: clean name of uploaded file, check for duplicate
$config['upload_path'] = DIR_UPLOAD_BANNER;

$file_parts = pathinfo($_FILES['cms_banner_image']['name']);

//Clean file name, replace all specialcharacters with dahs "-" $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $file_parts['filename']);

//Replace multiple dash with single $file_name = preg_replace('/-+/', '-', $file_name); $config['file_name'] = $file_name.'.'.$file_parts['extension'];

//Check for duplicate file names $counter = 0;
while (file_exists($config['upload_path'].$config['file_name'])) {
    $counter++;
    $config['file_name'] = $file_name.'_'.
                           $counter.'.'.
                           $file_parts['extension'];
}

Wednesday, November 18, 2015

Maps - enable scroll after first click on map only

Complete script for google map that will enable zoom on clicking in the map area only



<script type='text javascript' src="https://maps.googleapis.com/maps/api/js?key=&sensor=false&extension=.js">
<script type='text javascript'="">
    jQuery(document).ready(function(){
        var latitude = $('#map_latitude').val();
        var longitude = $('#map_longitude').val();
        // When the window has finished loading create our google map below
        google.maps.event.addDomListener(window, 'load', init);
        function init() {
            // Basic options for a simple Google Map
            // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
            var mapOptions = {
                // How zoomed in you want the map to start at (always required)
                zoom: 14,
                // The latitude and longitude to center the map (always required)
                center: new google.maps.LatLng(latitude,longitude),
                //Disable scroll wheel by default,
                scrollwheel: false,
                // How you would like to style the map.
                // This is where you would paste any style found on Snazzy Maps.
            // Get the HTML DOM element that will contain your map
            // We are using a div with id='map' seen below in the 
            var mapElement = document.getElementById('map');
            // Create the Google Map using out element and options defined above
            var map = new google.maps.Map(mapElement, mapOptions);
            var marker = new google.maps.Marker({

                map: map,

                position: map.getCenter(),

                icon: 'images/google-map-cion.png'

            });
            // Listen to click event on map and enable zoom
            map.addListener('click', function() {
                map.set('scrollwheel', true);
            });


        }
    })
    

</script>

DEMO