Monday, 16 February 2015

Prevent Sql Injection in PHP

Hi there! Today In this post I will mention few of the methods which is usually used in php application to prevent SQL injections.
It is said, “Never Trust Your User’s Input”. Preventing and cleaning user input in your php code is always a good and recommended practice.
1) Using mysql_real_escape_string() function:
Use if mysql_real_escape_string() is always a good practice into your code, but we can make it even better, consider following Code:

A BAD PRACTICE:

Example:

<?php

$uname = $_POST['username'];
$query = "SELECT password FROM tbl_user WHERE user_name = $uname "; // very hazardous, your system may prone to SQL injection
$res = mysql_query($query);

?>

A GOOD PRACTICE:
Example I:

<?php

$uname = mysql_real_escape_string($_POST['username']); //use of mysql_real_escape_string()
$query = "SELECT password FROM tbl_user WHERE user_name = '$uname' "; // use of single quotes for STRING $uname
$res = mysql_query($query);

?>

Example II:

<?php

$usrid = mysql_real_escape_string($_POST['userid']); //use of mysql_real_escape_string()
$usrid = (int)$usrid ; // cast id as int
$query = "SELECT username, password FROM tbl_user WHERE id = $usrid ";
$res = mysql_query($query);

?>

Also, if possible set your default charset to UTF8 using mysql_set_charset() function, it will be an another good approach.

2) PDO Prepared statements:

Following code will be quiet safe for pdo:


<?php
$stmt = $dbh->prepare("SELECT * FROM tbl_user where name = ?");
if ($stmt->execute(array($_POST['name']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
?>

3) Using mysqli prepared statement:

<?php

$city = $_POST['cname'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM tbl_city WHERE cty_name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);
    $stmt->fetch();
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Automatically Refresh HTML page or div after specific time Interval

There are several ways to refresh a complete HTML page after specific time interval, and same is the case with any specific Div or Span or any HTML element on a page, that we can refresh any specific part/element of HTML page without reloading the complete page.
First let’s take a look at refreshing HTML page after specific time interval, this can be achieved using either JavaScript or by meta tags.
A) Using Javascript:
You can use either of the following scripts to refresh after every 5 secounds, say:


Code I:

<script>

function autoRefresh()
{
window.location = window.location.href;
}

setInterval('autoRefresh()', 5000); // this will reload page after every 5 secounds; Method I
</script>

OR
Code II:


<script>

function autoRefresh1()
{
   window.location.reload();
}

setInterval('autoRefresh1()', 5000); // this will reload page after every 5 secounds; Method II
</script>

B) Refresh page using Meta tags
Its very easy, you just have to put a meta tag in head tag as follows:


<head>

<meta http-equiv="refresh" content="5" />
    <!-- This will refresh page in every 5 seconds, change content= x to refresh page after x seconds -->
</head>

Refresh Div/Span on HTML page after specific time:
In this part we will use JQuery to perform the task, as its provides few of the best options that can help us.
Suppose you have a div with ID as result similar to following:


<div id="result"></div>
Then JQuery code will be as follows:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
    $("#result").load("load.html");// a function which will load data from other file after x seconds
}

setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>

Similarly you can use $.ajax() or $.post() etc instead of load() function and put the response in a div or a span.
— Automatically Refresh HTML page or div after specific time Interval –

Saturday, 14 February 2015

Create a google map and display it on your wesite

Generate your own Google map for your Website, Blog or Facebook page. Just enter your address and copy a small snippett of code to your Generate your own Google map for your Website, Blog or Facebook page. Jusenter your address and copy a small snippett of code to your page. It's that easypage. It's that easy.

http://www.yourmapmaker.com/

CodeIgniter browser back button showing history fix

You may have noticed an issue while coding on CodeIgniter that even though you have destroyed the session values (invoking the $this->session->sess_destroy()) after logging out the page, the browser back button still takes you to your previous history page. Even though we may have made a provision to check empty session parameters and log out the page if the session has been destroyed, the browser back button still displays the previous pages that we have browsed.
The session check if we have used, tends to be working while refreshing the page, and doesn't let us browse new pages further. However, the back button lets us browse previous history items and it may raise an issue on privacy. User's private data may be visible to others too.
This occurs because the browser back button goes to the history when clicked.
We can prevent it by setting a header with no-cache. To prevent it, we should put the code given below in our index.php file with in the project.

header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");header("Cache-Control: no-store, no-cache, must-revalidate");

Print Page or Section of Page Using JQuery

We often need to print our output so that we can take a hard copy of that by printing it. To achieve this, we need to allow users to print a page or a section, div, span of HTML page. JQuery has a great plugin which is very easy to use and even allow us to tweak/configure printing. Here we are talking about JQuery.print.jswhich you can download from HERE.
Using this plugin we can print any Text content in a div or a span as shown below:
Usage is quiet simple:

Just include the main JS file along with JQuery:

<script type="text/JavaScript" src="path/to/jquery.print.js" />
And use below in document.ready() function

$("#myElementId").print(/*options*/);
or

$.print("#myElementId" /*, options*/);
Advance parameters are below:


$("#myElementId").print({
addGlobalStyles : true,
stylesheet : null,
rejectWindow : true,
noPrintSelector : ".no-print",
iframe : true,
append : null,
prepend : null
});

Sample Code:
Download JQuery.print.js and Put below code in your tag:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
            <script src="jQuery.print.js"></script>
            <script>
                $(document).ready(function() {
                    $(".print_div").find('button').on('click', function() {
                        var dv_id = $(this).parents(".print_div").attr('id');
                        //Print ele4 with custom options
                        $('#' + dv_id).print({
                            //Use Global styles
                            globalStyles: false,
                            //Add link with attrbute media=print
                            mediaPrint: false,
                            //Custom stylesheet
                            stylesheet: "http://fonts.googleapis.com/css?family=Inconsolata",
                            //Print in a hidden iframe
                            iframe: true,
                            //Don't print this
                            noPrintSelector: ".avoid-this"
                        });
                    });
                });
            </script>
            <div class="content">
                <div class="heading">
                    Print Page or Section of Page using JQuery
                </div>
                <div id='dv1'>
                    <div id='print-div1' class="print_div"><b>Print Text</b>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,<button class="print-link avoid-this"> Print this </button></div>
                    <div id='print-div2' class="print_div"><b>Print Text with Image  </b><img src="jquery-devzone.co.in.png" height="100" width="150"/>Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,<button class="print-link avoid-this"> Print this </button></div>
                    <div id='print-div3' class="print_div">
                        <b>Print Table  </b>
                        <style type="text/css">
                            table.gridtable {
                                font-family: verdana,arial,sans-serif;
                                font-size:11px;
                                color:#333333;
                                border-width: 1px;
                                border-color: #666666;
                                border-collapse: collapse;
                            }
                            table.gridtable th {
                                border-width: 1px;
                                padding: 8px;
                                border-style: solid;
                                border-color: #666666;
                                background-color: #dedede;
                            }
                            table.gridtable td {
                                border-width: 1px;
                                padding: 8px;
                                border-style: solid;
                                border-color: #666666;
                                background-color: #ffffff;
                            }
                        </style>
                        <table class="gridtable">
                            <tr>
                                <th>Header 1</th><th>Header 2</th><th>Header 3</th>
                            </tr>
                            <tr>
                                <td>Text 1A</td><td>Text 1B</td><td>Text 1C</td>
                            </tr>
                            <tr>
                                <td>Text 2A</td><td>Text 2B</td><td>Text 2C</td>
                            </tr>
                            <tr>
                                <td>Text 3A</td><td>Text 3B</td><td>Text 3C</td>
                            </tr>
                        </table>
                        <button class="print-link avoid-this"> Print this</button>
                    </div>
                </div>
                <div style="clear:both;"></div>
                <button class="print-link avoid-this" onclick="$('body').print({noPrintSelector: '.avoid-this'});"> Print Page </button>            </div></div>

Download Code Sample:
https://drive.google.com/file/d/0B-CQMvJeiunsS3BTcGhraVlVMlU/view?usp=sharing

Thursday, 7 August 2014

Script For Page Reload Page One Time After Loading the Page

Given Script load the page one time after loading the page ....

<script type='text/javascript'>

(function()
{
  if( window.localStorage )
  {
    if( !localStorage.getItem( 'firstLoad' ) )
    {
      localStorage[ 'firstLoad' ] = true;
      window.location.reload();

    }
    else
      localStorage.removeItem( 'firstLoad' );
  }
})();

</script>

Friday, 1 August 2014

Generating a Thumbnail from a YouTube Video

Websites, blogs and web applications regularly embed video content from various video service providers such as YouTubeand Vimeo. Videos are usually depicted using image thumbnails, tweaked to fit the graphics design of the website. When a video thumbnail is clicked, the actual video content starts playing.
 
In this post we wanted to explain how Cloudinary can help you to easily generate thumbnails from public videos. These thumbnails can be generated while applying any required image transformation in order to match your graphic design requirements.

Generating a Thumbnail from a YouTube Video

Let’s assume that we want to display the thumbnail of the following YouTube video:
 
This can be easily accomplished by adding the video ID to the URL. 'o-urnlaJpOA' in this example:
http://res.cloudinary.com/demo/image/youtube/o-urnlaJpOA.jpg