Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Tuesday, January 15, 2013

PHP Coding Tips


  • Use mysql_real_escape_string() function in MySQL Queries.
  • Remember to close the mysql connection at the end of the page using mysql_close().
  • Use comments for better understanding of large programs.
  • Prefer writing column names instead of * in select statement. Prefer writing column names instead of * in select statement.

    Select `fname`,`lname` from `users`
    Instead of
    Select * from `users`


  • Prefer writing comments in PHP rather than HTML because PHP comments are invisible from the browser source code but HTML comments are visible.
  • Avoid using multi-variable assignments unless not needed like:

  •             $var=$_POST[‘user’];
    $user=$_POST[‘user’];

  • Shorten the coding as much as possible. This will optimize the program and make the site faster.
  • Indent properly for the clarity of the program like

  • If($var==1) {
                            do something;
    }
    else { 
                            do something else;
    }

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 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');
?>