472,368 Members | 2,556 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,368 software developers and data experts.

Help me with Login System

28
Hi all, after thinking for sometimes, I thought it will be great opportunity to learn if I will start from scratch and build my own register/login system. Here is the thread that I will be posting the progress and I hope you guys will help me.

The code below is what I have so far. Just put two scripts in the same directory and that is! I hope you will help me
Thanks!
class.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. //php login sytem
  3. class LoginRegister{
  4.  function __construct(){
  5. }
  6.  
  7. function displogin($status){
  8. if ($status == "login"){
  9.     // post login page
  10.     $enc = base64_encode('login');
  11.     $html = <<<LOGIN
  12.     <form action = $_SERVER[PHP_SELF]?do=$enc, method = POST>
  13.         <p>Username: <input type=text name = username /></p>
  14.         <p>Password: <input type=password name = password /></p>
  15.         <input type=submit value=Login />
  16.     </form>
  17. LOGIN;
  18.         echo $html;
  19. }//end if
  20.  
  21. else if ($status == "register"){
  22.     //post register page
  23.     $enc = base64_encode('register');
  24.     $html = <<<LOGIN
  25.     <form action = $_SERVER[PHP_SELF]?do=$enc, method = POST>
  26.         <p>Username: <input type=text name = username /></p>
  27.         <p>Password: <input type=password name = password /></p>
  28.         <input type=submit value=Register />
  29.     </form>
  30. LOGIN;
  31.         echo $html;
  32. }// end elese if
  33.  
  34.  
  35. }
  36.  
  37. function auth($username, $password){
  38.     $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password' ";
  39.     $res  = mysql_query($sql) or die(mysql_error());
  40.     if (mysql_num_rows($res)==1){
  41.     echo "sucessful logged in as ". $username;
  42.     }//end if
  43.     else{
  44.         echo "<p style = 'color:red; font-weight:bold;'>Username or password not correct.
  45.         <br /> New? Register!</p>";
  46.         $this->displogin('register');
  47.     }// end else
  48. }
  49.  
  50.  
  51. function checkempty($username, $password, $mode){
  52.     if (empty($username) or empty($password)){
  53.     echo "<p style = 'color:red; font-weight:bold;'>Empty Values are not allowed</p>";
  54.     $this->displogin('login');
  55.     }//end if
  56.     else{
  57.     //do checking
  58.     switch($mode){
  59.         case 'login':
  60.         $this->auth($username, $password);
  61.         case 'register':
  62.         $this->adduser($username, $password);
  63.         default:
  64.             echo "<p style = 'color:red; font-weight:bold;'>Wrong Values are not allowed</p>";
  65.             $this->displogin('login');
  66.         }//end switch
  67.     }//end else
  68. }
  69.  
  70. function login($uname, $passwd){
  71.     //username
  72.     $username = stripslashes($uname);
  73.     $username = mysql_real_escape_string($uname);
  74.     //passsword    
  75.     $password = stripslashes($passwd);
  76.     $password = mysql_real_escape_string($passwd);
  77.     //check for empty variables
  78.     $this->checkempty($username, $password, 'login');    
  79. }
  80.  
  81. function register($uname, $passwd){
  82.     //username
  83.     $username = stripslashes($uname);
  84.     $username = mysql_real_escape_string($uname);
  85.     //passsword    
  86.     $password = stripslashes($passwd);
  87.     $password = mysql_real_escape_string($passwd);
  88.     //check for empty variables
  89.     $this->checkempty($username, $password, 'register');    
  90. }
  91.  
  92. function adduser($username, $password){
  93.     $sql = "INSERT INTO users(username, password) VALUES('$username', '$password')";
  94.     //redirect to login page
  95.     echo "<p style = 'color:green; font-weight:bold;'>Thanks for registering. You can now login</p>";
  96.     $this->displogin('login');
  97.     mysql_query($sql) or die(mysql_error());
  98. }
  99.  
  100. }//end class
  101. ?>
  102.  
index.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. require "class.php";
  3. $obj = new  LoginRegister();
  4. $conn = mysql_connect("localhost", "root", "") or die(mysql_error());
  5. mysql_select_db("admin", $conn)or die(mysql_error());
  6. if ((isset($_GET['do']))){
  7.     if (($_GET['do'])==(base64_encode('login'))){
  8.     $obj->login($_POST['username'], $_POST['password']);
  9.      }//end middle first if
  10.      else if(($_GET['do'])== (base64_encode('register'))){
  11.         $obj->register($_POST['username'], $_POST['password']);
  12.      }
  13.      else{
  14.          echo "<p style = 'color:red; font-weight:bold;'>Please Login</p>";
  15.         $obj->displogin('login');    
  16.         //debug
  17.         echo base64_encode('login').'<br />';
  18.         echo $_GET['do'];
  19.      }//end else middle
  20.  
  21. }//end last if 
  22. else{
  23.     echo "<p style = 'color:green; font-weight:bold;'>Please Login</p>";
  24.     $obj->displogin('login');    
  25. }//end else
  26. ?>
  27.  
Oct 31 '09 #1

✓ answered by TheServant

Sure. Let us know if you have a question. This section of Bytes is really for people who need some help with something specific. As much as we'd like to read through your code and impart some wisdom and knowledge in layout, syntax and method, proof reading code is not really in the job description. If you get an error, or something is not working as it should, post relavent code and all error messages and a full explanation, so we don't have to spend half our day looking through irrelevant code trying to find an unidentified problem.

If you're wanting to write a tutorial, write it in PHP insights.

13 4040
TheServant
1,168 Expert 1GB
Sure. Let us know if you have a question. This section of Bytes is really for people who need some help with something specific. As much as we'd like to read through your code and impart some wisdom and knowledge in layout, syntax and method, proof reading code is not really in the job description. If you get an error, or something is not working as it should, post relavent code and all error messages and a full explanation, so we don't have to spend half our day looking through irrelevant code trying to find an unidentified problem.

If you're wanting to write a tutorial, write it in PHP insights.
Nov 1 '09 #2
Apostle
28
this is newbie start writting the script. So IWhat I wanted is criticism and suggestion. I want to end up with full secure login system. That is my intention and I believe it is in Job descriptin ;)

Sorry for being vague and welcome for help :)
Nov 6 '09 #3
Dormilich
8,658 Expert Mod 8TB
knowledge has its price… either money (if you hire someone) or effort (to learn it yourself).
Nov 6 '09 #4
TheServant
1,168 Expert 1GB
@Dormilich
True. Apostle, you need to try and improve you script and come to us when you're stuck on something. Type in PHP login script, or login tutorial in Google and you'll have plenty of places to get the basics. Always start with the basics.
Nov 6 '09 #5
dlite922
1,584 Expert 1GB
@Apostle
You need some major help!

What you had is not even a class. Here's what real class looks like:


Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3. /**
  4. *  This class handles interactions for user access and registration
  5. * @date 11/06/2009
  6. * @author  Apostle 
  7. * @file LoginRegister.class.php    
  8. */
  9.  
  10. class LoginRegister
  11. {
  12.  
  13.     /**
  14.     * The DB object used to access the database
  15.     */
  16.     private $DB; 
  17.  
  18.  
  19.     /**
  20.     * Constuctor
  21.     * 
  22.     */
  23.     function __construct()
  24.     {
  25.         $this->DB = new DB(); 
  26.     }
  27.  
  28.     /**
  29.     * Authenticates a username and password and returns true or false depending on validity
  30.     * 
  31.     * @access public
  32.     * @param mixed $username
  33.     * @param mixed $password
  34.     * @return bool
  35.     */
  36.     public function authenticateUser($username, $password)
  37.     {
  38.         // initialize and clean variables
  39.         $cleanUser = mysql_real_escape_string($username); 
  40.         $cleanPass = mysql_real_escape_string($password); 
  41.  
  42.         // Run query and get results
  43.         $sql = "SELECT COUNT(*) AS count FROM users WHERE username = '$cleanUser' AND password = '$cleanPass' ";        
  44.         $result = $this->DB->query($sql); 
  45.  
  46.         // Parse result
  47.         if(!empty($result)) // if not empty
  48.         {
  49.             if($result[0]['count'] == 1) { // make sure count is one and only one user with the same username and passwword.
  50.                 return true; 
  51.             }
  52.         }
  53.  
  54.         return false;                 
  55.     } 
  56.  
  57.  
  58.     /**
  59.     * Registers a new user name and password and returns true of successful and false if not. 
  60.     * 
  61.     * @access public
  62.     * @param mixed $username
  63.     * @param mixed $password
  64.     * @return bool
  65.     */
  66.     public function registerUser($username, $password)
  67.     {
  68.         // initialize and clean variables
  69.         $cleanUser = mysql_real_escape_string($username); 
  70.         $cleanPass = mysql_real_escape_string($password); 
  71.  
  72.         // first check if this user already exists
  73.         if($this->checkUserExist($cleanUser))
  74.         {
  75.             die("Error: A user by this name already exists. You should have already run this check before and told the user before calling registerUser()");             
  76.             exit(0); // make sure you exit!
  77.         }
  78.         else
  79.         {
  80.             // user doesn't exist, add him:
  81.             $sql = "INSERT INTO users(username, password) VALUES('$cleanUser', '$cleanPass')";
  82.             $result = $this->DB->query($sql); 
  83.             if(empty($result)) 
  84.             {
  85.                     die("Something went wrong. Was not able to add user"); 
  86.             }
  87.  
  88.             return true;
  89.         }
  90.  
  91.         return false;
  92.     }
  93.  
  94.  
  95.     /**
  96.     * Checks if a user already exists, returns true if user already exists and false if no user exists with given username.
  97.     * 
  98.     * @access public
  99.     * @param mixed $username
  100.     * @return bool
  101.     */
  102.     public function checkUserExist($username)
  103.     {
  104.         // initialize and clean variables
  105.         $cleanUser = mysql_real_escape_string($username); 
  106.  
  107.         // query
  108.         $sql = "SELECT COUNT(*) AS count FROM users WHERE username = '$cleanUser'";
  109.         $result = $this->DB->query($sql); 
  110.  
  111.         // Parse result
  112.         if(!empty($result)) // if not empty
  113.         {
  114.             // we dont' care about the content, if there is a result this user exists
  115.             return true
  116.         }
  117.  
  118.         return false;     
  119.     }    
  120. }
  121.  
  122.  
  123.  

All your other functions should be in a different file that use this class. I'll leave that for you to learn.

* YOUR BIGGEST MISTAKE *

You did not validate the user input before inserting them in an SQL.

Imagine if I tried to login to your used any bogus user name this for a password: hack' OR 1 = 1 LIMIT 1;

Thus your SQL would look like this when executed:
Expand|Select|Wrap|Line Numbers
  1.  
  2. SELECT * FROM users WHERE username = 'hacker' AND password = 'hack' OR 1=1 LIMIT 1;' ";
  3.  
  4.  
Then your check, which says the number of results should be 1 return true because i'm sure you have at least one user name in your users table where the number 1 is always equal to 1. This is called

SQL INJECTION

Google the **** out of it. You're software is always unsecured without it.

I've done more than enough. I hope you learn PHP before you write unsafe software like this. I really REALLY hope you go read up on tutorials and practice programming and proper software testing before deploying any code.

Good luck,




Dan
Nov 7 '09 #6
Apostle
28
Thanks Dan for Postive criticism.
I completely rewrote the whole thing and will post it here. For now I it is Here
I will post it here.

The reason I want to write from the scratch is to learn new thing as I go, and I know there are many experts that can drill and expose my ignorance on something and definitely improve my skills.

So feel free to criticize me or advice me on anything (code, good coding habits et al)

Thanks for your time guys :)
Nov 7 '09 #7
TheServant
1,168 Expert 1GB
Writing from scratch is the best for learning, and that is what you should do. However, when you start spending time developing, you can't re-write everything (and have a life) so you will need to learn how to use and modify already tried and tested code.

Again, we're here to help when you get stuck, and generally we don't read through screens of code, but if you post snippets for specific problems, we'll mention any issues with the surrounding code no probs ;)
Nov 7 '09 #8
Apostle
28
Any recommended code that I can build upon? As per say, I'm beginner in these things and security matters alot in web apps :)
Nov 7 '09 #9
Dormilich
8,658 Expert Mod 8TB
currently the best measure against SQL Injection is using Prepared Statements (implemented in PHP’s MySQLi & PDO classes)
Nov 7 '09 #10
Apostle
28
I have learned a little on MYSQLi, I will check for PDO!
If you don't mind you can provide me a link. For now, I going to google
Nov 8 '09 #11
Dormilich
8,658 Expert Mod 8TB
MySQLi
PDO
_________________
Nov 8 '09 #12
Apostle
28
Thanks I'm going to check
Nov 8 '09 #13
dlite922
1,584 Expert 1GB
Learn OOP too while you're at it. Practice makes perfect. In the beginning working with already made code and reverse engineering it, modifying it, and especially improving and testing is the ultimate learning experience. That is how I learned PHP.

The reason I recommend OOP is I no longer see PHP as a scripting language and I use it for large applications.

In my opinion if someone wants to script, go learn Perl, PHP's sister. She's much much better at little scripts that make your life easier.

An advanced login script to me is an entry to a small to medium application. PHP/MySQL is a good choice for this.



Dan
Nov 9 '09 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

18
by: | last post by:
Please help. After a number of wrong turns and experiments I need advice on login management system to secure our web pages without inconveniencing our visitors or our internal staff. What I...
5
by: PaulThomas | last post by:
Working with XP-Pro and VS.Net I have set my Start Page to "Home.aspx" but the application always starts the "Login" page - - - How can I change the start page to the Home.aspx??? On the login...
4
by: Mike | last post by:
Please help this is driving me nuts. I have 2 forms, 1 user class and I am trying to implement a singleton class. Form 1 should create a user object and populate some properties in user. Form2...
8
by: Zelin Lu | last post by:
Hello, All I am building two user controls and dynamicly load one them into a PlaceHolder. But the button on the user control doesn't work fine. I need to click twice to fire the event? ...
9
by: Denise | last post by:
I have posted a similar message in 2 other forums but got no response. I have spent more hours than I can count researching this. Can anyone provide some insight...? Our ASP.Net application...
2
by: pv | last post by:
Hi everyone, I need help with following scenario, please: Users are accessing same web server from intranet (users previously authenticated in Active Dir) and from extranet (common public...
6
by: AppleBag | last post by:
I'm having the worst time trying to login to myspace through code. Can someone tell me how to do this? Please try it yourself before replying, only because I have asked this a couple of times in...
3
by: Porkie999 | last post by:
-----------------------------------------------------------------------QUESTION hi i am really stuck with this and its only a small problem. i want to be able to type ......... dsfsjfjsjjfs in...
1
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.