Wednesday, May 1, 2013

Secure login with MySQLi Extension php

In this post,  we create new code secure login script with MySQLi Extension (MySQL Improved) in php. may be useful for you

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


function LOGIN($username, $password)
{
               // Connect to database
            
                 $db = new mysqli('localhost', 'user', 'pass', 'demo');


               // Hash password with md5
                
                    $password = md5($password);
               
               // Construct SQL statement for query & execute 
                    
                    $tablename = "admin";
                    
                    $_Query = "SELECT username, password FROM ".$tablename." WHERE username = ? AND password = ? LIMIT 1";
                    
                    $stmt = $db->prepare($_Query) or die("Fatal Error !!");

                    $stmt->bind_param("ss", $username, $password);

                    $stmt->execute();
                    
                    $stmt->store_result();

               // bind variables to prepared statement 
    
                    $stmt->bind_result($col1, $col2); 
                    
                    $stmt->num_rows; 

               // fetch values 

                    $stmt->fetch();

               // If one row is returned, username and password are valid 
              
                    if (is_object($stmt) && $stmt->num_rows == 1)
                    { 
                            // Set session variable for login status to true 
                    
                            $_SESSION['logged_in_@d#i^'] = true; 
                            
                            $stmt->close(); // close statement

                            $db->close(); // close connection

                            header("secure-page.php?msg=welcome");

                    
                    } else { 

                            // If number of rows returned is not one, redirect back to login screen 
                            
                            $stmt->close(); // close statement

                            $db->close(); // close connection
                      
                            header("login.php");
                    
                    } 

               
}

?>

No comments:

Post a Comment