Thursday, August 29, 2013

Strange and Interesting facts about PHP

Comparison:
In PHP the boolean values TRUE and FALSE are case in-sensitive.

Example:
$a=TrUe;
if($a)
 echo 'Entered';     //will come
if($a==TRUE)
 echo 'Entered';    //will come
if($a===TRUE)
 echo 'Entered';   //will come

And TRUE = Something other than FALSE or 0 or '0'.

Example:
$a='test';
$b='0';
if($a==TRUE)
    echo 'Entered';   //will come
if($b==TRUE)
    echo 'Entered';   //will not come

Increment Operator:
If we use an increment operator along with a string, it will increment last letter of the string(When the last letter of the string is alpha numeric, that is other than special characters).

Example:
$a='apple3';
$b='apple';
$c='apple?';

echo ++$a;    // output: apple4
echo ++$b;   // output: applf
echo ++$c;   // output: apple?

Case Sensitive:
In PHP variables are case sensitive but functions are not.

Example:
$test='red';
echo $tesT;   // will not work
sample();      // will work

function Sample()
{
echo 'inside function';
}


Please go throw the following links for more details:
http://www.sitepoint.com/3-strange-php-facts-you-may-not-know/
http://php.net/manual/en/types.comparisons.php

Thursday, August 22, 2013

Javascript Local Storage

Reference: http://www.htmldog.com/guides/javascript/advanced/localstorage/

When building more complex JavaScript applications, it’s very useful to be able to store information in the browser, so that the information can be shared across different pages.

Unlike cookies, local storage can only be read client-side - that is, by the browser and your JavaScript. If you want to share some data with a server, cookies may be a better option.

Set Item: localStorage.setItem('name', 'tom');

Get Item: var name = localStorage.getItem('name');


Example:

<html>
      <head> 
              <title>Javascript Local Storage</title>
      </head>
      <body>
              Give some input to store on local: <input type="text" id="input_msg" />&nbsp&nbsp              <input type="button" value="Submit" id="submit" onclick="saveOnLocal();" />
              <br /><br />
              Data from local: <span id="local_data"></span>
      </body>
</html>

<script type="text/javascript">
function saveOnLocal()
{
var data=document.getElementById('input_msg').value;
localStorage.setItem('input_msg',data); //Set local storage
document.getElementById('local_data').innerHTML=localStorage.getItem('input_msg'); //Get local storage
 localStorage.removeItem('input_msg'); //Clear specific local storage item
 //localStorage.clear(); //Clear all local storage item

}
</script>

You can only save string using javascript local storage, use JSON for save array.

Example:
<script type="text/javascript">
localStorage.setItem('name', JSON.stringify(your_array));
var user = JSON.parse(localStorage.getItem('name'));
</script>


Browser support for local storage is not 100% but it’s pretty good - you can expect it to work in all modern browsers, IE 8 and above, and in most mobile browsers too. And the storage size depends on the browser.




Thursday, August 8, 2013

Get file size using Java Script only

HTML:
<input type="file" name="photo" id="photo" />

Java Script:
$('#photo').live('change', function(){
      var file_size=this.files[0].size;
      alert(file_size);
});

Notes:
1. This is a HTML5 feature. So I think its only works on HTML5 supported browsers.
2. Similarly we can get some attribute of file.

Source:
http://stackoverflow.com/questions/8192516/html5-file-browse-tag
http://forum.jquery.com/topic/how-to-validate-file-size-function-before-submitting-form

Wednesday, July 24, 2013

Apply Even and Odd classes for elements on, "while" or "for" loop

When we display list of elements using any looping, we need to add some two classes for differentiate one row from another. On this case we need use one extra variable, and increment it throw loop, then we can get '0' or '1' by mod(%) this value. So now we can have two different classes repeatedly like 'r0','r1'. And now write style for these two classes.

Example:
<style type="text/css">
Output
.list0{
background-color: #00B2C1;
}
.list1{
background-color: #50D4FF;
}
</style>
<html>
<title>Even and Odd classes for loopig elements</title>
<body>
<table cellspacing="0">
<tr>
<td>NO</td>
<td>Name</td>
</tr>
<?php $i=0; while($i<=10) { ++$i; ?>
<tr class="list<?php echo (++$x%2); ?>">
<td><?php echo $i; ?></td>
<td>Name <?php echo $i; ?></td>
</tr>
<?php } ?>
</body>
</html>


Note: Here we can use '$i' to mod. But most of cases we don't has this option, and more over here we wrote single line(++$x%2) to get mod value.

Monday, July 22, 2013

Regular Expression validation for frontend(JS) and backend(PHP)

Start with one example:

For validate Name Field: Alphabets, numbers and space(' ') no special characters min 3 and max 20 characters.

var ck_name = /^[A-Za-z0-9 ]{3,20}$/; 
if (!ck_name.test(name))
{
        alert('Enter valid Name.');
        return false;
}


Note: The above code for front end using JavaScript. If you are using PHP use key word preg_match instead of test.

Some important conditions:
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
{3,10} Check for the string length in between give boundary.


Important Links:


Wednesday, July 10, 2013

Implement "Remember Me" option for login using Javascript(JQuery) cookies

1. Get JQuery Cookie library in hand

To implement this first you need to have JQuery Cookie library. So please save following JS file as "jquery.cookie.js", or you can directly download from Github .

//Save it as jquery.cookie.js
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
 if (typeof define === 'function' && define.amd) {
  // AMD. Register as anonymous module.
  define(['jquery'], factory);
 } else {
  // Browser globals.
  factory(jQuery);
 }
}(function ($) {

 var pluses = /\+/g;

 function raw(s) {
  return s;
 }

 function decoded(s) {
  return decodeURIComponent(s.replace(pluses, ' '));
 }

 function converted(s) {
  if (s.indexOf('"') === 0) {
   // This is a quoted cookie as according to RFC2068, unescape
   s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  }
  try {
   return config.json ? JSON.parse(s) : s;
  } catch(er) {}
 }

 var config = $.cookie = function (key, value, options) {

  // write
  if (value !== undefined) {
   options = $.extend({}, config.defaults, options);

   if (typeof options.expires === 'number') {
    var days = options.expires, t = options.expires = new Date();
    t.setDate(t.getDate() + days);
   }

   value = config.json ? JSON.stringify(value) : String(value);

   return (document.cookie = [
    config.raw ? key : encodeURIComponent(key),
    '=',
    config.raw ? value : encodeURIComponent(value),
    options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    options.path    ? '; path=' + options.path : '',
    options.domain  ? '; domain=' + options.domain : '',
    options.secure  ? '; secure' : ''
   ].join(''));
  }

  // read
  var decode = config.raw ? raw : decoded;
  var cookies = document.cookie.split('; ');
  var result = key ? undefined : {};
  for (var i = 0, l = cookies.length; i < l; i++) {
   var parts = cookies[i].split('=');
   var name = decode(parts.shift());
   var cookie = decode(parts.join('='));

   if (key && key === name) {
    result = converted(cookie);
    break;
   }

   if (!key) {
    result[name] = converted(cookie);
   }
  }

  return result;
 };

 config.defaults = {};

 $.removeCookie = function (key, options) {
  if ($.cookie(key) !== undefined) {
   // Must not alter options, thus extending a fresh object...
   $.cookie(key, '', $.extend({}, options, { expires: -1 }));
   return true;
  }
  return false;
 };

}));



2. Add "Remember Me" check box on Login page

Add "Remember Me" check box in login form, then include "jquery.cookie.js" and your JS file (here: login.js).

<input type="text" id="username" /><br />
<input type="password" id="password" /><br />
<input type="checkbox" id="c1" />Remember Me<br />
<input type="submit" id="loginsubmit" />
.
.
.
<script src="js/jquery.cookie.js"></script>
<script src="js/login.js"></script>


3. Set and Get Cookie using JQuery

Now, set entered username on cookie, or display username if already avail on cookie. To do this,
include following line in your JS file (here: login.js)

$(document).ready(function()
{

// Please read these set of code after you read next set. So that you can understand simply.
var username=$.cookie("username");   // Get username from cookie on form load.
if(username!=undefined)
{
$('#loginsubmit').val(username);   // Display username on input box if avail on cookie.
      $('#c1').prop('checked', true);  // Check check box manually by us. So that duration for current email will reset.
}

// Read this set first.
$('#loginsubmit').click(function()
{
      if($('#c1').is(':checked')) // If user checked remember me check box
{
                var email=$('#loginsubmit').val(); // Get entered username or email
                //  Set username on cookie when login form submit.
$.cookie("username", email, { expires: 365 });  // Remember username for 1 year.
}
      // Your other codes...
}

});


Note:
1. Assign username or email to cookie after you done form validation like email validation, empty checking, so that you can sure for stored value are original.

2. And here we set username or email on cookie for one year. You don't need to worry about like "will expire after one year?". Because it will reset to one year whenever user try to login. And only go empty once if the user not login even one time for a year. You can change this duration as you need.

Wednesday, June 26, 2013

Differents between rand() / mt_rand () in PHP

rand() :

          Slow process, max allowed length smaller than mt_rand(), may has dubious or unknown characteristics, can get max limit by getrandmax(), using old technique.

          Syntax:  int rand(min,max);
          Example: echo rand(0,500);         // return value between 0 to 500 (including 0 and 500)

mt_rand():

         Four times faster than rand(), had large max length, return known characteristics, can get max limit by mt_getrandmax().

          Syntax:  int mt_rand(min,max);
          Example: echo rand(100,99999);         // return value between 100 to 99999

Conclusion:

          In my point of view mt_rand() is better than rand() in any cases.

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS...