Saturday, December 3, 2011

Nodejs - Web's new weapon!

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

This is new thing in town and will be finest armor in your armory. It is easy to learn as it is almost same as Javascript and Python. There is a sample video tutorial on Nodejs site, which tells how easy it is to create a chat server. Once you will learn I can bet you will feel like you can do anything now.

There are several APIs based on it like Pusher, Platform as a Service Nodester and you will find many more things upon Google it. I will come with some good tutorial for it in some time later. Explore it and let me know if you find something interesting based on it.

Javascript Prototype

Javascript prototype is very useful thing. Say, we want to perform some sort of transformation or something else on string  like we want to find some pattern matching for validation. Example below is based on this.


Requires: Javascript

Using:


Explanation:
   Line 2: We created a prototype object for string named found and equate it to null.
   Then in the code below it we find the pattern 'str' insensitive of case.

   Line 3: We create str as String.

   Line 17: Then we gave value to 'found' which can be used further.

Note: Line 3 is important here as prototype for String is given, so str = 'my string' will not work. We have to declare it as String type. Same is to be done if it is being used with other type or custom types.

JSON - Javascript Object Notation

There were days when we used to create and use XML for transporting and store data and it was good at it. But I consider there was a problem with it getting data from it, I feel nausea. I used 'was' here because I also consider it as the way our daddies used to transfer data. Now is the day of JSON.

JSON is cool, easy, requires less memory(though we are not bothered). You can use it with any language and I love it. Frankly, I gave up XML before learning it because of JSON.

JSON looks like array we make in C\C++ or any other language. As we are familiar with the array, it makes understanding of JSON easy.

Syntax: {'data' : ['J','S','O','N'], 'this' : { 'is' : 'json' } }

Let's use it with PHP and Javascript.

PHP:
  1. $array = new array('data'=>array('J','S','O','N'), 'this'=>'json');
  2. $json = json_encode($array);
  3. $json = json_decode($json);
  4. echo $json->data[0];                             //output: J
  5. echo $json->this;                                   //output: json
Javascript:
  1. var json = {'data' : ['J','S','O','N'], 'this' : { 'is' : 'json' } };
  2. alert(json['data'][0]);                            //output: J
  3. alert(json->data[0]);                            //output: J
  4. alert(json->this);                                  //output: json
  5. alert(json['this']);                                  //output: json
We have studying here for PHP and Javscript as it is used mostly for web development. Go to json.org for better understanding and using with other languages.

Friday, November 25, 2011

Self ssl certification of the site

Continuation to previous post about enabling SSL, which is needed to use Google SMTP and other things. This post will help you in getting your site SSL certificate, so that Facebook API can be used, which now requires HTTPS protocol. Below are the steps to give your localhost a local SSL certificate.
  1. Open the DOS command window and change directory to bin directory of wamp apache directory by using the DOS command without quotes: “cd /d c:\” and then “cd wamp\bin\apache\apache2.2.8\bin”. apache2.2.8 should be changed to what apache folder your wamp server has. After done, the DOS prompt should look like:
    C:\wamp\bin\apache\apache2.2.8\bin>
  2. Create a server key with 1024 bits encryption. You should enter this command without quotes:
    “openssl genrsa -des3 -out server.key 1024″.
    It’ll ask you a pass phrase, just enter it.

  3. Remove the pass phrase from the RSA private key (while keeping a backup copy of the original file). Enter this command without quotes:
    “copy server.key server.key.org”
    and then
    “openssl rsa -in server.key.org -out server.key”
    It’ll ask you the pass phrase, just type it.

    You’ll fill in the information after entering this command. The correct location of config file, openssl.cnf may need to be changed. In windows, you won’t see “.cnf” extension of the file openssl, but in DOS you’ll see the full name openssl.cnf.

  4. Create a self-signed Certificate (X509 structure) with the RSA key you just created. Enter the command without quotes:
    “openssl req -new -x509 -nodes -sha1 -days 365 -key server.key -out server.crt -config C:\wamp\bin\apache\apache2.2.8\conf\openssl.cnf”.

  5. In the conf folder of apache2.2.8 folder, create two folders named as ssl.key and ssl.crt. Copy the server.key file to ssl.key folder and server.crt file to ssl.crt.

  6. In httpd.conf file, remove the comment ‘#’ at the line which says:
    LoadModule ssl_module modules/mod_ssl.so

  7. In httpd.conf, remove the comment ‘#’ at the line which says:
    Include 
    conf/extra/httpd_ssl.confThen move that line after this block
    <IfModule ssl_module>…. </IfModule>

  8. Open the php.ini file located in apache2.2….\bin folder, remove the comment ‘;’ at the line which says: extension=php_openssl.dll

  9. Edit the httpd_ssl.conf file in the folder name, extra.
    1. Find the line which says “SSLMutex ….” and change it to “SSLMutex default” without quotes.
    2. Find the line which says: <VirtualHost _default_:443>. Right after it, change the line which says “DocumentRoot …” to DocumentRoot “C:/wamp/www/” with quotes. Change the line “ErrorLog….” to Errorlog logs/sslerror_log. Change the line “TransferLog ….” to TransferLog logs/sslaccess_log.
    3. SSL crt file: Change the line “SSLCertificateFile ….” to SSLCertificateFile “conf/ssl.crt/server.crt”.
    4. SSL key file: Change the line “SSLCertificateKeyFile ….” to SSLCertificateKeyFile “conf/ssl.key/server.key”.
    5. Change the line which says <Directory “C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin”> or something similar to <Directory “C:/wamp/www/”> and add the following lines inside those <Directory … >…</Directory> tags:
      Options Indexes FollowSymLinks MultiViews
      AllowOverride AllOrder allow,denyallow from all
    6. Make sure the line CustomLog
      “logs/ssl_request_log”
      is uncommented (remove the #). This step is suggested.

  10. In the previous DOS Command windows, enter httpd -t . If it displays Sysntax is OK, then go to Step 11. If not, then correct the wrong syntax and redo step 9.

  11. Restart the Apache server. This is most important step.

  12. If restart is successful, then open the browser and enter “https://localhost” without quotes.
Note: 
          Follow the above steps carefully and you'll be done.
          This will work for Linux too. Just use the path to www folder.
          For original certification there are lot many organizations like Verisign.
          For firefox go to options and add that certificate to your browser.

Wednesday, November 23, 2011

Configuring SSL on Apache

Our local server run on HTTP protocol. Then how will you work with facebook APIs where you need secured protocol now to work with APIs. Well its very easy to configure WAMP for ssl. Follow the steps below and you are done with it.


  1.  Left click on wamp icon in taskbar in windows and go to apache->apache modules and select ssl_module.
  2. Left click on wamp icon again. php->php extensions. Select php_openssl.
  3. Most important restart your wamp and you are done.
For those who want to configure by editing file do the following.
  1. Open httpd.conf in apache->conf folder.
  2. Uncomment the line saying or write 'LoadModule ssl_module modules/mod_ssl.so' minus the quotes(').
  3. Uncomment the line php.ini file in apache folder 'extension=php_openssl.dll' minus quotes(').
  4. Save  the doument and restart apache.
Configuring php for ssl is done by editing php.ini.
  1. Open the php.ini in PHP folder.
  2. Uncomment the line 'extension=extension=php_openssl.dll'.
  3. Save it restart the server.

Saturday, November 5, 2011

Zomato.com

Zomato.com is a new buzz on internet for foodies. They provide lists of restaurant through many filters like your location, by cuisine, by name(of course). Over it there are many more filters so you can choose the restaurant of your choice. They currently provide service in 10 major cities of India. You can download app for android, iphone, blackberry and nokia/symbian or you can visit at m.zomato.com on mobiles.

For website developers they have a search widget which can be embedded in site. Customize size of the widget according to the need of site and embed it using the script they provide.

From a point of view of web developer, content placement on the site is very good and the color combination of shades of dark red and shades of grey is also great. That is why the site looks cleaner.

Zomato has released their API publicly. Here we will talk about the API of zomato, not all but one of them. The API is very easy to use.

Requires:
Zomato API key, PHP, JSON

Using:
Let the key be 'api'. Now we would like to have names of cities where they provide service.
  1. <?php 

  2.  $cities = json_decode(get_file_contents("https://api.zomato.com/v1/cities.json?apikey=api"));
  3.  echo $cities->city[0]->city->name;
  4.  
  5. ?>
Explanation:

       3. 'apikey' is must in the url because it has to be parsed to get the JSON. The 'api' is to be replaced with
           you api key given by zomato. Function json_decode() will turn that JSON in a stdClass object.

       4. Data can be fetched from the object like the syntax in this line. Its similar to calling object variables or
           methods as done in class objects.

Note: SSL has to be enabled on your server, because look at the url it has 'https' which is secured.
         Respect the privacy of the users and read zomato policies before taking the application
         online.

So, go to zomato build your own application about restaurants, their menus and much more. This is a great site to find place where you will like to eat what you want to eat.

Saturday, October 22, 2011

All new HTML- HTML5

HTML 5 has come up with some super cool tags, which makes things(coding) easier and reduces the use of third party applications(flash, Adobe is going to launch Adobe Edge in near future which generates code in jQuery, HTML 5, CSS). Here are some of the tags which are revolutionary.

iframe: It is not related to Steve Jobs or Apple at all! ;) Well it is super awesome tag. It works like page in some page. Place it where ever you want. Try it, you gonna love it.
Syntax: <iframe src="somefile.html">Not supported by browser</iframe>

audio: Before this we used to use third party tools for audio. This lets you embed audio without any problem in your webpage.
Syntax: <audio controls="controls"><source src="somefile.mp3" type="audio/mp3" />Not supported by webbrowser</audio>

video: Same as audio just the tag name is changed and source type.
Syntax: <video controls="controls"><source src="somefile.mp4" type="audio/mp4" />Not supported by webbrowser</audio>

progress: Many times we brainstorm over progress bar. Here it is, very simple to use and looks pretty cool, basically dependent on OS you are using.
syntax: <progress value="40" max="100"></progress>

header: This creates header and it knows where it should be.
syntax: <header><p>Some thing some thing</p></header>

footer: This places footer in the webpage. But personally I don't understand its behaviour.
syntax: <footer>Some thing</footer>

nav: Now you don't need to write extra CSS for making navgation, like inline.
syntax: <nav><a href="1.html">One</a><a href="2.html">Two</a></nav>
Tip: Use nav with header and footer.

localStorage: HTML 5 also worked towards replacement of cookies. This stores data on client computer just as cookies but you can store large amount of data. Because whatever is needed can be fetched alone. It requires javascript to work.
syntax: <script type="text/javascript">localStorage.name = 'James Bond'</script>

sessionStorage: This is just like session but again created by javascript. It is also cool thing as you can understand.
syntax: <script type="text/javascript">sessionStorage.name = 'James Bond'</script>

canvas: This is the ultimate thing of all. You can draw on your web page now using this element. This works just as canvas in real but coding part. It has some easy calling involved for making lines, rectangle and other. This also uses javascript to create. Go on google HTML 5 games. You can create wonder using this. But first of all you need to read all about it.
syntax: <canvas id="mycanvas"></canvas>

Note: This is not all read about these tags, they have lot of things.
          You can see dive into HTML 5. Everything is explained beautifully.

Creating HTML elements dynamically

There are times when we want to create HTML elements on the page, result of a certain action. Below is explained how to do that using Javascript.
I have written a javascript which you can download. Please read "README" before using it.

Required: Javascript, HTML.

Using:
    1. <script type="text/javascript">
    2.       var i = 0;
    3.       function creatediv()    
    4.      {
    5.             i++;
    6.             var newelement = document.createElement('div');
    7.             newelement.setAttribute('id', i);
    8.             newelement.innerHTML = 'This is newly created div.';
    9.             var parentelement = document.getElementById('presentdiv')
    10.             parentelement.appendChild(newelement);
    11.             //var firstchild = parentelement.firstChild;
    12.             //parentelement.insertBefore(newelement, firstchild);
    13.              
    14.      }
    15. </script>
    16. <html>
    17. <body>
    18.              <div id="presentdiv">This div is present here from the moment the page is opened.<input type="button" value="Click to create new div" onclick="javascript:creatediv();"></div>
    19. </body>
    20. </html>
Explanation:
First, we see the div 'presentdiv'. It has two nodes, first is the text node and another is input 'button'. New div is created on clicking button. How?
Look at the javascript function creatediv().

          6: A new div is created using createElement(). It takes the HTML tagname of element to be created as argument.

          7: setAttribtue() sets the attribute of the element using it. Like we have set 'id' as i, which is incrementing on every click.

          8: innerHTML is used if you want to add text to the element. Mostly used with div.

          9: We saved parentelement i.e., 'presentdiv' for further use instead of calling again and again.

          10: appendChild() is called to append  the element we just created, div(i). It appends at the end of the 'parentelement'.

          11: This line is used if we want to add new element at the beginning of parent element. 'firstChild' returns the first child of the 'parentelement'.

          12:  insertBefore() is used if new element is to be inserted before the some element we know. Here we insert 'newelement' before 'firstchild'.

Note: 
    Uncomment the line 11 and 12 if you want to insert 'newelement' before 'firstchild'.
    Also see lastChild and returning values of firstChild and lastChild.

Friday, October 21, 2011

Fetching from database using PHP

If you have database, then of course you will need to fetch data out of it. Four methods are described below to fetch from database and whats the difference between them.

Required: PHP, MySQL.

Using:

table1
name(varchar)

$query = "SELECT name FROM table1";
$rows = mysql_query($query);
$row = mysql_fetch_array($rows, $result_type); 
$row = mysql_fetch_assoc($rows);
$row = mysql_fetch_row($rows);
$row = mysql_fetch_object($rows, 'class', $params);

Note: All parameters are not defined here but are explained below.

Explanation:
Methods to fetch are described below:
  1. mysql_fetch_array($rows, $result_type): First argument, $rows is same as we have described earlier. Second argument is the result type which has three values MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH, which is default and this argument is optional.
    • MYSQL_ASSOC is used when we want to use associative key or table name for fetching. So, if we want to echo result it would be like
      echo $row['name'];
    • MYSQL_NUM is used if we are going to use numbers as associative keys also called index. It would go like
      echo $row[0].
    • MYSQL_BOTH is used if you don't know what you are going to use. With this way you can use both key and index.
  2. This is just the same as mysql_fetch_array() with result type argument as MYSQL_ASSOC. Syntax will be
    $row['name'];
  3. It is identical to mysql_fetch_array() with result type as MYSQL_NUM. Syntax will be
    echo $row[0];
  4. mysql_fetch_object($rows, 'class', $params): This is same as mysql_fetch_assoc() but instead of array this returns object of class 'class'. That is it can be accessed by only with column name in table. Syntax would be:
    echo class->name;
    The last argument, $params, is used when parameters are needed to be passed in constructor of 'class', it has to be array. Also $params is optional.
Note: All the fetch function are almost equivalent in terms of performance.
         Also see PHP manual on these function.

Wednesday, October 12, 2011

Creating a menu

Well there are two ways to create menu that I can think of. One is the Google's way, you click on it to get the menu items. Other is which we see on other sites when you hover on menu and it shows you the menu items.
But we will go the Google's way.

Required: Javascript, HTML

Using:
    1. <html>
    2. <script type="text/javascript">
    3. var toggle = 1; 
    4. function showmenuitems()
    5. {
    6.    if(toggle == 1)
    7.    {
    8.       document.getElementById('menuitems').style.visibility = 'visible';
    9.       toggle = 0;
    10.    }
    11.    else
    12.    {
    13.       hidemenuitems();
    14.       toggle = 1;
    15.    }
    16. }
    17. function hidemenuitems()
    18. {
    19.       document.getElementById('menuitems').style.visibility = 'hidden';
    20. }
    21. </script>
    22. <body>
    23. <p id="menu" onclick="showmenuitems()">Menu</p>
    24. <dl onblur="hidemenuitems()" id="menuitems" style="visibility:hidden; z-index:1">
    25. <dt>Item1</dt>
    26. <dt>Item2</dt>
    27. </dl>
    28. </body>
    29. </html>
Explanation:
If you will read the code you will find that all is done is using the visibility property of the dl. Here toggle variable helps us to determine the current state. A lot can be done with this code. For ex: if you click on the document except the paragraph menu items should hide, adding href to items etc etc.

Note: It is just basic way to implement the menu. Use your imagination to create something new.

Saturday, October 8, 2011

Comparing timestamp in MySQL

Required: MySQL

Using:
table1
         id (int)
         jointime(timestamp)

SQL query
  1. SELECT id FROM table1 WHERE jointime > '2011-10-08 00:00:00';
Explantion:
  1. This query selects id from table where jointime is greater than 2011-10-08.
Note:
  • Timestamp is a standard data type in MySQL and it should have both date and time.
  • For current time use NOW()
  • If you are using only date then use conversion from date to timestamp using TIMESTAMP()
  • With PHP
    • First get the time if current time use time(), it will give time in Unix Epoch.
    • Convert above time to timestamp using date() and then use in query.
    • If using some other time use mktime().
  • Remember the quotes they are important.
Also see MySQL timestamp datatype and PHP date time functions, also other functions.

Friday, October 7, 2011

Cool front page

There is a site on internet  We Are Empire. This site has pretty cool front page. Page is pretty descriptive too plus it don't irritate the user by reloading for new content. Some other site like this which I personally liked is Nike's nike better world site. It takes a little while to load but every information is on just single page and designed in awesome way using HTML5, z-index and many more things. We will come to it some other time.

But we will talk about the former one here. After running a console over the site, I understood what they had done. Well its nothing but Javascript and applaud to the maker, it is used very well for designing. It do not have flash.
  1. What they had done is when you click on the front logo which is image it shows you next div which is hidden behind it and hide the top div. 
  2. Now you see 4 bubbles. Thats interesting now margin of the image in background of the bubble changes when you hover it while hiding the overflow. This is a good thing, must have taken long time to do that.
  3. Open at the bottom is the coolest thing. Click on it and another page comes with no page loading. Again is the game of margin. Margin-top is changed using Javascript to animate.
  4. There are smaller effects also like close appearing and hiding, get in touch etc.
So, this is how this front page is working. Try making yours with such innovation.

Here is a example of that a very short one.

  1. <script type="text/javascript">
  2. function anim(mydiv)
  3. {
  4. var i = 0;
  5. while(i < 10)
  6. {
  7.         mydiv.style.marginTop = 10*i + 'px';
  8.         i++;
  9. }
  10. }
  11. </script>
  12. <div id="mydiv" onclick="javascript:anim(this)">
  13. test
  14. </div>

Protection from sql injection in PHP

There are many points which are needed to stop sql injection in PHP. One of them is discussed below.
We will focus on escaping the characters which allow sql injection. Let say we have a table:

Required: MySQL, PHP

Using:
table1:
         id (int)
         name (char)

Now if we use a query,

"SELECT id FROM table1 WHERE name = ".$name;

Here $name is a php vairable. Now lets try to hack this query. I will use one example here for that.
If we pass a value ALL (SELECT name FROM table1) into $name and it will reply to us with all the ids in table1. So in order to prevent such disaster we are going to use some methods of PHP itself.

First, is the mysql_real_escape_string() and the second one is addslashes().
While running query use the above functions like  addslashes(mysql_real_escape_string($name)).

Explanation:

mysql_real_escape_string() - what it does is escape the special characters in string. like hexadecimal.
addslashes() - this introduces slashed before the quotes.

Note:

  1. First use mysql_real_escape_string() then addslashes over it if you are entering value in database.
  2. To invert the procedure which will be needed when fetching values use stripslashes() twice over the value and it will give you the original value.

Thursday, October 6, 2011

Refreshing a particular div

Required: jquery-latest.js

Using:



Explanation:
              9. # is selector for id which is newcontent, a div here. Load method loads the content of file2.php in newcontent div.

file2.php
Note: Try not to write any HTML just process your data using php.

Text suggestion while writing in textbox using Javascript

Requirements: None, just javascript but good knowledge of that.

Using:
file.html
  1. <html>
  2. <body>
  3.       <input type="text" id="notrequired" onKeyUp="hint(this)" />
  4.        <div id="hintwords"></div>
  5. </body>
  6. <script type="text/javascript">
  7. function hint(me)
  8. {
  9. var arr = new Array('test','it','will','work');
  10. var iter = 0;
  11. var mat = new Array();
  12. var len = me.value.length;
  13. if(len>0)
  14. {
  15. for(iter=0 ; iter < arr.length; iter++)
  16. {
  17. var val = me.value;
  18. //alert(val);
  19. var patt = new RegExp( val ,'gi');
  20. var result = patt.exec(arr[iter]);
  21. if(result == val)
  22. {
  23. //alert(arr[iter]);
  24. mat.push(arr[iter]);
  25. }
  26. }
  27. //alert(mat[0]);
  28. var str = '';
  29. for(iter = 0; iter < mat.length ; iter++)
  30. {
  31. if(str == '')
  32. {
  33. str = str + mat[iter]
  34. }
  35. else
  36. {
  37. str = str + ',' + mat[iter]
  38. }
  39. }
  40. document.getElementById('hintwords').innerHTML = str;
  41. }
  42. else
  43. {
  44. document.getElementById('hintwords').innerHTML = '';
  45. }
  46. }
  47. </script>
  48. </html>
Explanation:
           I will be explaining just the lines that are important and needed to be explain.
     9.   array is created of the words that are needed to be hinted.
    13.  checking if the length of value of text in textbox is greater than 0.
    15.  looping on the length of the array of words.
    20.  making a regular expression using of the value of textbox. Here the regex generated will be the same as the value of textbox.
     21. checking for the match using exec() of regex.
     26. if there is match then the word that is from the array of word is pushed into new array mat.
     35. if the str has no value then this line is exceuted and string is concatenated to str.
     39. else this line concatenated to str.
     42. is just writing the str in the div hintwords.
     46. if the textbox has no value or empty then no hint is shown

                                                                                        Jquery post method for JSON in php files

                                                                                        Required: jquery.js(I use jquery-1.6.js. Download latest!)

                                                                                        Using: In file1.php


                                                                                          1. $(document).ready(function(){
                                                                                          2.           $.post( 'filename', {data : data}, function(data , status){ 
                                                                                          3.                      if(status == 'success')
                                                                                          4.                     { alert(data.name); //your code } 
                                                                                          5.           }, "json" );
                                                                                          6. });


                                                                                        In file2.php

                                                                                          1. if(isset($_POST['data'])){
                                                                                          2.         echo json_encode(array('name'=>$_POST['data']));
                                                                                          3. }
                                                                                        Explanation:
                                                                                         file1.php

                                                                                          1. checks if the current document is ready.
                                                                                          2. is the jquery method "post" is given arguments, first is the "filename" is the file name which you want to handle the post variables. Second is associative array sort of thing in which first "data" is name of the post variable and second "data" is the value of the variable. Third argument is the callback function, this executes when the post is complete. This function is provided two arguments, first is "data" which is the response from the file which is handling post. We will explain it after sometime. And the second is "status" it is optional in all of this without this code will still work. It actually holds the status of response.
                                                                                          3. checks if status is success
                                                                                          4. if status is success we use alert to check for the JSON value which is data.name and will alert "data" because we sent it back from file2.php.
                                                                                          5. "json" is the last argument of the post method which tells the that this method is expecting JSON as response.
                                                                                        Note: post variable name can be in quotes 'data'.
                                                                                                 argument status can be omit.
                                                                                                 "json" is required as argument if you want response to be JSON.

                                                                                        file2.php
                                                                                          1. checks if $_POST['data'] is set. The data index is the same variable name we have sent from file1.php.
                                                                                          2. first we create an associative array with key as "name" and value as $_POST['data']. Then we encode it in JSON using json_encode and echo it, which is accepted by first file in callback function as data and checked using alert in file1.php as data.name which is the key in associative array.
                                                                                        Note:
                                                                                                this file should not have any of HTML code.
                                                                                                this file should not echo anything other than JSON.
                                                                                                you can use include() but above two points should always hold.


                                                                                        Hope this will help you in case you find trouble.