Posted By

codingforever99 on 10/19/13


Tagged

login php html


Versions (?)

make php login script


 / Published in: PHP
 

URL: http://function-code.blogspot.com/2013/04/make-php-login-script.html

How to build a login form using php with mysql database.

  1. //================================================ db.php
  2. <?php
  3. $DB_hostname = "hostname";
  4. $DB_user = "username";
  5. $DB_password = "password";
  6. $DB_name = "dbname";
  7.  
  8. $DB_link =mysqli_connect($DB_hostname,$DB_user,$DB_password,$DB_name)
  9. or die ("error : can't connect database !!");
  10.  
  11. mysqli_set_charset($DB_link, 'utf8');
  12. ?>
  13.  
  14.  
  15. //================================================ login.php
  16. <?php
  17. include("db.php");
  18. header('Content-type: text/html; charset=utf-8');
  19.  
  20. if($_SERVER["REQUEST_METHOD"] == "POST")
  21. {
  22. $myusername=mysqli_real_escape_string($DB_link, $_POST['username']);
  23. $mypassword=mysqli_real_escape_string($DB_link, $_POST['password']);
  24.  
  25. // to validate username (length between 5 and 20) (contaning characters A-Z or a-z or _)
  26. if (!preg_match('/^\w{5,20}$/', $myusername)){
  27. echo '<B><FONT SIZE="4" COLOR="#FF0000">error: bad username</FONT></B>';
  28. }
  29. else{
  30. // to encrypt login password, also password stored in database is encrypted.
  31. $md5_password = md5($mypassword);
  32.  
  33. $sql="SELECT * FROM user_tb WHERE login='$myusername' and password='$md5_password'";
  34. $result=mysqli_query($DB_link, $sql);
  35. $row=mysqli_fetch_array($result);
  36. $count=mysqli_num_rows($result);
  37.  
  38. if($count==1)
  39. {
  40. $_SESSION['login_user']= $myusername;
  41. $_SESSION['login_name']= $row['name'];
  42. header("location: index.php");
  43. }
  44. else
  45. {
  46. echo '<B><FONT SIZE="4" COLOR="#FF0000">incorrect login or password </FONT></B>';
  47. }
  48. }
  49. }
  50.  
  51. ?>
  52. <form action="" method="post">
  53. <label>user login :</label><input type="text" name="username"/><br>
  54. <label>Password :</label><input type="password" name="password"/><br>
  55. <input type="submit" value=" Submit "/><br>
  56. </form>
  57.  
  58.  
  59. //================================================ logout.php
  60. <?php
  61. header("Location: login.php");
  62. ?>
  63.  
  64.  
  65. //================================================ index.php
  66. <?php
  67. header('Content-type: text/html; charset=utf-8');
  68.  
  69. $S_login_user = $_SESSION['login_user'];
  70. $S_login_name = $_SESSION['login_name'];
  71.  
  72. if(!isset($S_login_user))
  73. header("Location: login.php");
  74.  
  75. ?>
  76. <body>
  77. <h1>Welcome :<?php echo $S_login_name; ?></h1>
  78. <A HREF="logout.php">logout</A>
  79. </body>

Report this snippet  

You need to login to post a comment.