Saturday, December 22, 2012

Using Encrypted Passwords in PHP Login Script


Suppose someone breaches into our database, he can easily get the users ‘username’ and ‘passwords’. To avoid this situation we use encrypted passwords.

Even if someone enters into our database, he cannot get the password. When a user wants to login, his password is converted into the same format and matched with the database encrypted password. If both usernames and encrypted passwords match, then user will be logged in.

Usually, md5() function is used to encrypt the passwords. It generates a 32 characters word. Following code of PHP Login System shows the implementation of the function.

Database Table of users

Id
user
pass
1
userone
b7e055c6165da55c3e12c49ae5207455
2
usertwo
c4d8a57e2ca5dc5d71d2cf3dbbbbaabe

After submitting the login credentials, the following script will handle the login request.               

$user=$_POST['user'];
$pass=md5($_POST['pass']); //This is the only change

//checks if a user exists in database having `user` and `pass` equal to $user and $pass respectively.
$chkqry=mysql_query("select `id` from `users` where `user`='".$user."' and `pass`='".$pass."'");

//if user exists then, set cookie `SessionId` and redirect to home.php page
if(mysql_num_rows($chkqry)>0) {
      setcookie("SessionId",$user,0);
      header('location:home.php');
}

//if user doesn’t exist then, shows message ‘Incorrect Username or Password’ on login.php page
     else {
           header('location:login.php?msg=Incorrect Username or Password');
     }


Tuesday, December 18, 2012

Using Marquee in HTML


Horizontal Marquee – Used for making a sliding text from left to right or right to left.

<marquee direction="left" scrollamount="2" onmouseover="this.stop();" onmouseout="this.start();" scrolldelay="0">
Hey, its great.
</marquee>

Description of attributes:
“direction” : - specifies the direction of the scroll. ‘left’, ‘right’ for Horizontal Marquee and ‘up’, ‘down’ for vertical  scrolling.
“scrollamount” : - specifies the speed of scrolling.
“scrolldelay”: - for delay between repetition.
“onmouseover” calls the inbuilt javascript function ‘this.stop()’ for stopping the scrolling when mouse is over the block.
“onmouseout” calls the inbuilt javascript function ‘this.start()’ for again starting the scrolling when mouse is moves out of the block.

Vertical Marquee – It is used for making auto-scroll of blocks (Ex. News blocks). The following script automatically scrolls the block’s content from down to up direction. It eliminates the overhead of JavaScript.

<marquee direction="up" scrollamount="2" onmouseover="this.stop();" onmouseout="this.start();" height="100px;" style=="width:100px;"   scrolldelay="0">
Line 1<br />
Line 2<br />
Line 3<br />
Line 4<br />
Line 5<br />
Line 6<br />
Line 7<br />
Line 8<br />
Line 9<br />
Line 10<br />
</marquee>

Automatic Image Slideshow using JavaScript/JQuery


The following is a simple script used to make slideshow of images through JavaScript/JQuery. Through this, the overhead of flash can be easily removed.

Download: Source Code

<html>
<head>
<!-- 'jquery-1.7.2.js' can be downloaded from Internet. Contains basic Javascript Libraries -->
<script language="javascript" src="jquery-1.7.2.js"></script>
<!-- Slideshow javascript code starts -->
<script type="text/javascript">
// An array of images
var imgs = ["image1.jpg","image2.jpg","image3.jpg","image4.jpg","image5.jpg"];
// cnt contains the total number of images.
var cnt = imgs.length;
//function runs on page load. It runs Slider() function in every 3 seconds
$(function() {
           setInterval(Slider, 3000);
     });
     //Slider() function fades out the previous image slowly and fades in the next image.
function Slider() {
//The src attribute of <img> with id "imageSlide" changes to the next image name with fading effect.
     $('#imageSlide').fadeOut("slow", function() {
     $(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
     });
}
</script>
<title> Untitled </title>
</head>
<body>
<!-- It contains the image with image5.jpg as the initial Image. -->
<img id="imageSlide" alt="" src="image5.jpg" />
</body>
</html>



Friday, December 14, 2012

Simple Clock using JavaScript




Download: Source Code

Save the following script as “index.html”

<!-- ##### Basic HTML Doctype statement #####-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- ##### Head block starts #####-->
<head>
<!-- ##### Selects the default timezone #####-->
<? date_default_timezone_set('Africa/Abidjan'); ?>
<!-- ##### Javascript functions #####-->
<script type = "text/javascript">
<!-- ##### function h() for calculating current hour value #####-->
function h()
     {
           //today variable contains complete date string
           var today = new Date();
           //today.getHours() function fetches only the hours from the date
           var h = today.getHours();
           //it prints the hour in div with id ‘hours’
           document.getElementById("hours").innerHTML = h;
     }
<!-- ##### function m() for calculating current minute value #####-->
function m()
     {
           var today = new Date();
           //today.getMinutes() function fetches only the minutes from the date
           var m = today.getMinutes();
           //it prints the minutes in div with id ‘minutes’
           document.getElementById("minutes").innerHTML = m;
     }
<!-- ##### function s() for calculating current second value #####-->
function s()
     {
           var today = new Date();
           //today.getSeconds() function fetches only the seconds from the date
           var s = today.getSeconds();
           //it prints the seconds in div with id ‘seconds’
           document.getElementById("seconds").innerHTML = s;
     }
<!-- ##### function ms() for calculating current milli-second value #####-->
function ms()
     {
var today = new Date();
           //today.getMilliseconds() function fetches only the milli-seconds from the date
           var ms = today.getMilliseconds();
           //it prints the milli-seconds in div with id ‘mseconds’
           document.getElementById("mseconds").innerHTML = ms;
     }
<!-- ##### function time() calls the above four functions #####-->
function time()
     {
           h();
           m();
           s();
           ms();
     }
<!-- ##### function update() calls the time() function in every .01 seconds means it updates the time in every 0.01 second #####-->
function update()
     {
           //setInterval() function containing two parameters par1 (function) and par2 (time-interval) calls par1 in every par2 milliseconds
           setInterval("time()",10);
     }
     // for running the time() function first time.
     time();
               
</script>
<!-- ##### link tag attaches the css stylesheet to the html to improve the look of the page #####-->
<link rel="stylesheet" href="style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clock</title>
</head>
<!-- ##### update() function is called as soon as the page is loaded #####-->
<body onload="update();">
<!-- ##### “header” block contains the Heading and any message you want to give. #####-->
<div class="header">
  <div id="sitename">Clock</div>
  <div id="content">Message : <? //echo $message; ?></div>
</div>
<div class="container">
  <div class="input" id="input">
  <div id="mainbox">
  
    <div id="box">
      <!-- ##### “hours” block is left blank and is updated according to current hour. #####-->
      <span id="hours"></span><br />
      <span style="font-size:12px;">Hours</span>
    </div>
    <div style=" float:left; color:#FFF; margin:15px;"> : </div>
   
    <div id="box">
      <!-- ##### “minutes” block is left blank and is updated according to current minute value. #####-->
<span id="minutes"></span><br />
      <span style="font-size:12px;">Minutes</span>
    </div>
    <div style=" float:left; color:#FFF; margin:15px;"> : </div>
   
    <div id="box">
     <!-- ##### “seconds” block is left blank and is updated according to current second value. #####-->
      <span id="seconds"></span><br />
      <span style="font-size:12px;">Seconds</span>
    </div>
    <div style=" float:left; color:#FFF; margin:15px;"> : </div>
   
    <div id="box">
<!-- ##### “mseconds” block is left blank and is updated according to current millisecond value. #####-->
      <span id="mseconds"></span><br />
      <span style="font-size:12px;">Mili-Seconds</span>
    </div>
  </div>
  </div>
</div>
<div class="footer">
<hr />
  <span id="copy">&copy; All rights reserved.</span>
  <span id="developer">Developed by: Aman Dhanda</span>
</div>
</body>
</html>
------------------------------------------------------------------------
The following is the style sheet is attached to the script. Save it as “style.css” in the same folder. Its just for making your page attractive.

@charset "utf-8";
/* CSS Document */
body { overflow:hidden; background:#333; }
.header { height:100px; background:#CCC; left:0px; right:0px; margin:-10px -10px 20px -10px; border-bottom:solid 2px #999; }
#sitename { color:#225; font-size:24px; font-family:Arial, Helvetica, sans-serif; margin:10px 0px 10px 40px; padding:10px; }
#content { margin:10px 0px 10px 60px; color:#666; font-size:16px; }
.container { margin:0 auto; width:700px; padding:20px; }
.input { font-size:18px; color:#999; }
#mainbox {text-align:center; color:#003; font-family:Arial, Helvetica, sans-serifet, sans-serif; font-weight:100; font-size:36px;}
#box { float:left; text-align:center; border:solid medium #EEE; background:#CCC; padding:10px 30px;}
input { border:solid thin #003; height:30px; width:200px;  font-size:18px; color:#030; }
select { height:30px; font-size:18px; color:#030; }
select#dd { width:50px; }
select#mm { width:150px; }
select#yyyy { width:100px; }
select#tz { width:300px; }
input#submit { height:30px; font-size:18px; width:100px; color:#030; }
.footer { position:absolute; bottom:0px; width:98%; color:#FFF; }
#copy { left:0px; float:left; }
#developer { right:0px; float:right; }

Tuesday, December 11, 2012

SQL Injection attack and prevention

Attack

Let’s take the case of Login System in which a person logins using his username and password. The following SQL query authorizes the user. In this query, a user can logs in if and only if there exists a row in `users` table having the `user` and `pass` value equal to the posted value.

               $user=$_POST['user'];
      $pass=$_POST['pass'];
               $chkqry=mysql_query("select `id` from `users` where `user`='".$user."' and `pass`='".$pass."'");

Suppose, if the user enters the following username and password in the Login Box fields.

                Username           :               anyword’ OR ‘a’=’a
                Password            :               anyword’ OR ‘a’=’a

Then the query is as follows,

                $chkqry=mysql_query("select `id` from `users` where `user`='anyword’ OR ‘a’=’a’ and `pass`='anyword’ OR ‘a’=’a’”);

This is always true and returns all the rows of the table results in logging of the user.
This is SQL Injection.

Prevention

The function mysql_real_escape_string() in PHP escapes the special characters like quotes (), double-quotes() etc. That is the function converts the characters as follows:

     ‘    ->   \’
     “    ->   \”

This is best method to prevent SQL Injection Vulnerability.

Saturday, December 8, 2012

How to make simple login system using PHP

Download : Source Files

Requirements

       You should have following environments installed:
      PHP
      MySQL Database
      Apache Server
       Any internet browser
       Notepad or any other text editor.

4 Files are created

       Login Page (login.php)
       Authentication Page (auth.php)
       Home Page (home.php)
       Logout Page (logout.php)

Database and Table Information

Host Name: localhost
User: root
Password: “NULL”
Database: database_name
Table: users
Id
user
pass
1
userone
testpassword1
2
usertwo
testpassword2

Login Page (login.php)

<html>
<head>
            <title>Login Page</title>
      </head>
      <body>
            <?php
                  //shows message if incorrect username or password
                  if(isset($_REQUEST['msg'])) {
                        echo $_REQUEST['msg'];
                  }
            ?>
            <form action="auth.php" method="post" name="loginForm">
                  Username: <input type="text" name="user" /><br />
                  Password: <input type="password" name="pass" /><br />
                  <input type="hidden" name="submitting" value="true" />
                  <input type="submit" name="login" value=" Login " />
            </form>
      </body>    
</html>

Authentication Page (auth.php)

<?php
//check if the form is submitted
if(isset($_POST['submitting'])) {
     //connection to database started
     $conn=mysql_connect("localhost","root","");
     $db_select=mysql_select_db("database_name",$conn);
     //connection to database ended
     $user=$_POST['user'];
     $pass=$_POST['pass'];
     //checks if a user exists in database having `user` and `pass` equal to $user and $pass respectively. (Check out prevention from SQL Injection)
     $chkqry=mysql_query("select `id` from `users` where `user`='".$user."' and `pass`='".$pass."'");
     //if user exists then, set cookie `SessionId` and redirect to home.php page
     if(mysql_num_rows($chkqry)>0) {
           setcookie("SessionId",$user,0);
           header('location:home.php');
     }
     //if user doesn’t exist then, shows message ‘Incorrect Username or Password’ on login.php page
     else {
           header('location:login.php?msg=Incorrect Username or Password');
     }
}
?>

Home Page (home.php)

<?php
     //if cookie is not set, redirect to login.php
     if(!isset($_COOKIE['SessionId'])) {
           header('location:login.php');
     }
?>
Hello <?php echo $_COOKIE['SessionId'];?>, You are logged in.<br />
For Logging out, <a href='logout.php'>Click Here</a>

Logout Page (logout.php)

<?php
     //unsets cookie by setting cookie to some previous time -1000.
     if(isset($_COOKIE['SessionId'])) {
           setcookie('SessionId','',-1000);
     }
     //then go back to login.php
     header('location:login.php');
?>