SitePoint Sponsor

User Tag List

Results 1 to 25 of 25

Thread: Login Script

  1. #1
    SitePoint Enthusiast mvtiturbo's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Login Script

    Is there an easy way to allow users to login just with a password and a username?

    Ive seen Myrealm but im not sure on how you can set it so only specified passwords and loginnames work.

    If anyone knows how to do a basic script that maybe stores the passwords and loginnames in MYSQL database let me know

    Thanks

  2. #2
    My precious!!! astericks's Avatar
    Join Date
    Mar 2002
    Location
    Vancouver, BC
    Posts
    1,971
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    look for kevin yank's tutorials on sitepoint.com

    he has one tut for authentication.

    As for login scripts, it would really depend on your needs. Check out hotscripts.com you might get some good ones.

  3. #3
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here you go. (you just need to make the register.php file)

    [File: users.sql]
    Code:
    CREATE TABLE users (
         uid     INTEGER AUTO_INCREMENT NOT NULL,
         username VARCHAR(15) NOT NULL,
         password VARCHAR(15) NOT NULL,
    KEY users_key (uid)
    );
    [File: login.php]
    PHP Code:
    <?php

         
    // Initialize Session
              
    session_start();

         
    // Check for previous authentication
              
    if ( isset($_SESSION['auth']) )
              {
                   
    $loc 'members.php?PHPSESSID' session_id();
                   
    header("location:$loc");
                   exit;
              }

         
    // Error Messages
              
    $msg = array();
              
    $msg['login'] = 'You have to login before you can access member content';
              
    $msg['invalid'] = 'Username/password does not match';
              
    $msg['logout'] = 'You have been successfully logged out';

         
    // Check for error
              
    if ( isset($_GET['reason']) && in_array($_GET['reason'],$msg) )
              {
                   
    $el $_GET['reason'];
                   echo 
    '<font color="#FF0000"><b>' $msg[$el] . '</b></font><br />'
              }

    ?>

         <form action="process_login.php" method="post">
         Username <input type="text" name="username" value="" /><br />
         Password <input type="password" name="password" value="" /><br />
         <input type="submit" name="do_login" value="Login" />
         </form>
    [File: process_login.php]
    PHP Code:
    <?php

         
    // Initialize Session
              
    session_start();

         
    // Check for previous authentication
              
    if ( isset($_SESSION['auth']) )
              {
                   
    $loc 'members.php?PHPSESSID=' session_id();
                   
    header("location:$loc");
                   exit;
              }

         
    // Database Connection
              
    $dbh = @mysql_connect('your_server','your_username','your_password');
              if ( !
    $dbh )
              {
                   die (
    'Database Error - Connect');
              }
              @
    mysql_select_db('your_database',$dbh);

         
    // Get Form Contents
              
    if ( isset($_POST['do_login']) )
              {
                   
    $username trim($_POST['username']);
                   
    $password trim($_POST['password']);

                   
    $sql "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 0,1";

                   
    $result = @mysql_query($sql);
                   if ( !
    $result )
                   {
                        die(
    'Database Error - Query');
                   }
                   if ( 
    mysql_num_rows($result) == )
                   {
                        
    $_SESSION['auth'] = 1;
                        
    $_SESSION['username'] = $username;
                        
    $loc 'members.php?PHPSESSID=' session_id();
                        
    header("location:$loc");
                        exit;
                   }
                   else
                   {
                        
    $loc 'login.php?reason=invalid';
                        
    header("location:$loc");
                        exit;
                   }

              }
              else
              {
                    
    $error_loc 'login.php?reason=login';
                    
    header("location:$error_loc");
                    exit;
              }
    [File: members.php]
    PHP Code:
    <?php

         
    // Initialize Session
              
    session_start();

         
    // Check for previous authentication
              
    if ( !isset($_SESSION['auth']) )
              {
                   
    $loc 'login.php?reason=login';
                   
    header("location:$loc");
                   exit;
              }

              echo 
    'Welcome ' $_SESSION['username'] . '<br />';
              echo 
    '<a href="logout.php">Logout</a>';

    ?>
    [File: logout.php]
    PHP Code:
    <?php

         
    // Initialize Session
             
    session_start();

         
    // Destroy Session
              
    $_SESSION = array();
              
    session_destroy();

         
    // Redirect to login.php
              
    $loc 'login.php?reason=logout';
              
    header("location:$loc");
              exit;

    ?>
    that has some added stuff, but i was bored. it should work good, if it doesnt, sorry, i'm tired.

  4. #4
    SitePoint Addict Mower's Avatar
    Join Date
    Feb 2004
    Location
    Aussie Aussie Aussie
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Talking Good Code less server strain

    Ok here is Mowers way to solve this problem

    Now moonchild posted some ok code ;P , but mine is better

    AND can be done in HTML TOO!!!

    Code:
     
    <!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>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <p align="center" class="style2">DO YOU REALY HAVE ACCESS TO THIS PAGE?</p>
    <p align="center"><a href="./pageyouwant.html">YES</a> || <a href="./pagetosaybuggeroff.html">NO</a> </p>
    <p align="center">&nbsp;</p>
    <p align="center">&nbsp;</p>
    </body>
    </html>


    "Will I ever find my way to GURU?"

  5. #5
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Mower
    Now moonchild posted some ok code ;P , but mine is better
    Hey! :P Give a guy some credit! I've been awake for 24 hours, and I'm getting told old to stay up this long! Mine wasn't that bad. :P I use classes though, so I can't even guarantee it's right. It's been a long time since I hard coded mysql functions.

  6. #6
    SitePoint Enthusiast mvtiturbo's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    <?php

    // Initialize Session
    session_start();

    // Check for previous authentication
    if ( !isset($_SESSION['auth']) )
    {
    $loc = 'login.php?reason=login';
    header("location:$loc");
    exit;
    }

    echo 'Welcome ' . $_SESSION['username'] . '<br />';
    echo '<a href="logout.php">Logout</a>';

    ?>
    Is there anyway of when the user enters a correct password they can be directed to a page called "Mainpage"?

    Thanks

  7. #7
    SitePoint Addict Mower's Avatar
    Join Date
    Feb 2004
    Location
    Aussie Aussie Aussie
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    it was only a joke moonchild

    Nar m8 your right,

    Mine was only a joke LOL

    how could anyone secure a page with only html??? LOL

    Mine relises on an honesty system, to which all humans are right???

    BAHAHAHAHAHA

    by what I have seen of yours its looks great, and I would never pass comment on a script that exceeds my skill level, hence the Joke?

    Have a good one and nice code


    "Will I ever find my way to GURU?"

  8. #8
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mvtiturbo
    Is there anyway of when the user enters a correct password they can be directed to a page called "Mainpage"?

    Thanks
    [File: process_login.php]
    PHP Code:
    <?php 

         
    // Initialize Session 
              
    session_start(); 

         
    // Check for previous authentication 
              
    if ( isset($_SESSION['auth']) ) 
              { 
                   
    $loc 'Mainpage.php?PHPSESSID=' session_id(); // <-- LOOK HERE
                   
    header("location:$loc"); 
                   exit; 
              } 

         
    // Database Connection 
              
    $dbh = @mysql_connect('your_server','your_username','your_password'); 
              if ( !
    $dbh 
              { 
                   die (
    'Database Error - Connect'); 
              } 
              @
    mysql_select_db('your_database',$dbh); 

         
    // Get Form Contents 
              
    if ( isset($_POST['do_login']) ) 
              { 
                   
    $username trim($_POST['username']); 
                   
    $password trim($_POST['password']); 

                   
    $sql "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 0,1"

                   
    $result = @mysql_query($sql); 
                   if ( !
    $result 
                   { 
                        die(
    'Database Error - Query'); 
                   } 
                   if ( 
    mysql_num_rows($result) == 
                   { 
                        
    $_SESSION['auth'] = 1
                        
    $_SESSION['username'] = $username
                        
    $loc 'Mainpage.php?PHPSESSID=' session_id(); // <-- LOOK HERE
                        
    header("location:$loc"); 
                        exit; 
                   } 
                   else 
                   { 
                        
    $loc 'login.php?reason=invalid'
                        
    header("location:$loc"); 
                        exit; 
                   } 

              } 
              else 
              { 
                    
    $error_loc 'login.php?reason=login'
                    
    header("location:$error_loc"); 
                    exit; 
              }
    is that what you are wanting?

  9. #9
    SitePoint Enthusiast mvtiturbo's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello

    yes thats exactly what i needed to know.

    It seems to work well, although it doesnt tell the user when they log out although it looks like this is included in your .php file.

    I think its in the $MSG array, they dont seem to be displaying for some reason!

    // Error Messages
    $msg = array();
    $msg['login'] = 'You have to login before you can access member content';
    $msg['invalid'] = 'Username/password does not match';
    $msg['logout'] = 'You have been successfully logged out';
    None of the above show up, i.e when the user enters a password that isnt in the database and when they log out and when they click login, Any ideas?

    If you have an answer to why its not doing that then thats cool, otherwise ill keep it just how it is.

    Thanks very much for your help so far though!

    Thanks

  10. #10
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you enter an invalid username/password, does it redirect to the login page again with the querystring set?

    Try this

    [File: login.php]
    PHP Code:
    <?php 

         
    // Initialize Session 
              
    session_start(); 

         
    // Check for previous authentication 
              
    if ( isset($_SESSION['auth']) ) 
              { 
                   
    $loc 'members.php?PHPSESSID' session_id(); 
                   
    header("location:$loc"); 
                   exit; 
              } 

         
    // Error Messages 
              
    $msg = array(); 
              
    $msg['login'] = 'You have to login before you can access member content'
              
    $msg['invalid'] = 'Username/password does not match'
              
    $msg['logout'] = 'You have been successfully logged out'

         
    // Check for error 
              
    if ( isset($_GET['reason']) && !empty($_GET['reason']) ) 
              { 
                   
    $error $_GET['reason']; 
                   echo 
    '<font color="#FF0000"><b>' $msg[$error] . '</b></font><br />'
              } 

    ?> 

         <form action="process_login.php" method="post"> 
         Username <input type="text" name="username" value="" /><br /> 
         Password <input type="password" name="password" value="" /><br /> 
         <input type="submit" name="do_login" value="Login" /> 
         </form>
    try this and let me know if it works.

  11. #11
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    for some reason i can never get in_array() and array_search() to ever work properly, or i'm just using them wrong.

  12. #12
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    UK
    Posts
    147
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    [File: process_login.php]
    PHP Code:
    <?php

         
    // Initialize Session
              
    session_start();

         
    // Check for previous authentication
              
    if ( isset($_SESSION['auth']) )
              {
                   
    $loc 'members.php?PHPSESSID=' session_id();
                   
    header("location:$loc");
                   exit;
              }

         
    // Database Connection
              
    $dbh = @mysql_connect('your_server','your_username','your_password');
              if ( !
    $dbh )
              {
                   die (
    'Database Error - Connect');
              }
              @
    mysql_select_db('your_database',$dbh);

         
    // Get Form Contents
              
    if ( isset($_POST['do_login']) )
              {
                   
    $username trim($_POST['username']);
                   
    $password trim($_POST['password']);

                   
    $sql "SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 0,1";

                   
    $result = @mysql_query($sql);
                   if ( !
    $result )
                   {
                        die(
    'Database Error - Query');
                   }
                   if ( 
    mysql_num_rows($result) == )
                   {
                        
    $_SESSION['auth'] = 1;
                        
    $_SESSION['username'] = $username;
                        
    $loc 'members.php?PHPSESSID=' session_id();
                        
    header("location:$loc");
                        exit;
                   }
                   else
                   {
                        
    $loc 'login.php?reason=invalid';
                        
    header("location:$loc");
                        exit;
                   }

              }
              else
              {
                    
    $error_loc 'login.php?reason=login';
                    
    header("location:$error_loc");
                    exit;
              }


    Should there not be a ?> at the end of that code?

  13. #13
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    UK
    Posts
    147
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is the session id needed in the url eg $loc = 'members.php?PHPSESSID=' . session_id();

    ?

  14. #14
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    UK
    Posts
    147
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I had this going fine on 1 site but on another it won't login It finds the user from the database (well afaik because if I put in the correct user it does back to the login with a "you must login" message where as when I put it a non existant user it comes up with "user/password doesnt match") Any ideas?

  15. #15
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    UK
    Posts
    147
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmmm, even the script above (apart from the db connection) works fine on 1 site but not on the other. Could it be to do with setting on the site?

  16. #16
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    UK
    Posts
    147
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No one? Can the not working site be rejecting sessions or not setting them?

  17. #17
    SitePoint Member
    Join Date
    May 2004
    Location
    uk
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm probably missing something here but can I easily convert this to use with PHPMyAdmin?

  18. #18
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by phoenix1
    I'm probably missing something here but can I easily convert this to use with PHPMyAdmin?
    what do you want to convert?

  19. #19
    SitePoint Addict moonchild's Avatar
    Join Date
    Nov 2003
    Location
    U$A
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SQHell
    Is the session id needed in the url eg $loc = 'members.php?PHPSESSID=' . session_id();

    ?
    i am not sure, i do it out of habit.

  20. #20
    SitePoint Member
    Join Date
    Jun 2004
    Location
    uk
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Questions 1: What I have to put into header of some other pages to "log" into?

    Questions 2: What would like be a code of adding members into mysql table from up and editing it through some php logon page...with and without encryption the password?

    moonchild ... any tips?

  21. #21
    gimme the uuuuuuuuuuu duuudie's Avatar
    Join Date
    Feb 2004
    Location
    Switzerland
    Posts
    2,253
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi
    might it be of any help?



    you will create say... your 'login' table.
    Code:
    CREATE TABLE `login` (
      `userID` mediumint(11) unsigned NOT NULL auto_increment,
      `username` varchar(25) NOT NULL,
      `password` varchar(50) NOT NULL,
      PRIMARY KEY  (`userID`)
    )
    Here is a simple login script:
    PHP Code:

    <?php 
    session_start
    (); 

    //get the data used to authenticate users 

    $username trim(addslashes($_POST['username'])); 
    //without encryption:
    $password trim(addslashes($_POST['password'])); 
    //with encryption 
    $password md5($_POST['password']); 

    //if you use encryption. make sure that you will first record your user password like this:
    //$password = md5($_POST['password']); 

    //perform the query to see if you have a matching result 

    $sql mysql_query
    "SELECT userID 
    , username 
    , password 
    FROM login 
    WHERE username = '
    $username
    AND password = '
    $password
    LIMIT 0,1"

    or die(
    '<p>Unable to query the database at this time.<br />Error: ' mysql_error() . '</p>'); 
    $row mysql_fetch_array($sql); 

    if(
    mysql_num_rows($sql) == 1// if there is one matching result, then get some data to be displayed on your pages for the user logged in. 

        
    $_SESSION['userID'] = $row['userID']; 
        
    $_SESSION['username'] = $row['username']; 
        
    $_SESSION['loggedin'] = TRUE// Setting session var 'loggedin' to true--> check it on top of each you want to be protected. 
           
        
    header('Location:http://www.yoursite.com/welcome.php'); // redirects to the welcome page if everything is ok. always use absolute URL!! 
        
    exit; 
           
    }else{ 
        
    header('Location:http://www.yoursite.com/error.php'); // Redirect to error page. 
        
    exit; 

    ?>
    Then use this code on top of each page you want to be protected:
    PHP Code:

    if ($_SESSION['loggedin'] == TRUE) { 
    //display page 

    else { 
    //redirect to another page, like index or login... 



    for a much more complex auth system, check out this article:

    http://www.sitepoint.com/article/ant...access-control

  22. #22
    gimme the uuuuuuuuuuu duuudie's Avatar
    Join Date
    Feb 2004
    Location
    Switzerland
    Posts
    2,253
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    just in case, here is the login form:
    Code:
    <form action="checklogin.php" method="post">
    username: <input type="text" name="username" size="10" />
    password: <input type="password" name="password" size=10 />
    <input type="submit" value="go" />
    </form>
    now if you need to add new users, use the table shown above, and use the below code.
    here is the form:
    Code:
    <form action="addnewmember.php" method="post">
    username: <input type="text" name="username" size="10" />
    password: <input type="password" name="password" size=10 />
    <input type="submit" value="go" />
    </form>
    here is the addnewmember.php relevant code:
    PHP Code:
    $username trim(addslashes($_POST['username'])); 
    //without encryption: 
    $password trim(addslashes($_POST['password'])); 
    //with encryption 
    $password md5($_POST['password']); 


    //perform the query to see if you have a matching result 

    $sql mysql_query
    "INSERT INTO
    login
    SET 
    username = '
    $username' '
    , password = '
    $password' ' 
    LIMIT 0,1"

    or die(
    '<p>Unable to query the database at this time.<br />Error: ' mysql_error() . '</p>'); 

  23. #23
    SitePoint Member
    Join Date
    Jun 2004
    Location
    uk
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes I wanted to have something like admin page where I could add new member, change existing user or password etc...view all users, modify alter, update and/or delete some of them

  24. #24
    gimme the uuuuuuuuuuu duuudie's Avatar
    Join Date
    Feb 2004
    Location
    Switzerland
    Posts
    2,253
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if you can make the above script run and if you understand how it works, doing what you want to do will be easy.

    this link will help you for sure:

    http://www.sitepoint.com/article/pub...mysql-data-web

    Don't forget to check the Kevin Yank's article mentionned above as well.


  25. #25
    SitePoint Member
    Join Date
    Jun 2004
    Location
    uk
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    And how now to decrypt...encrypted ...hashed password with md5... when I'm trying to log in?

    or to say like...

    is it true that with Hashing I can only encrypt the text/numbers etc. but I cannot get the originals back.

    If it is true..what I can do to encrypt password of new adding members into database ... when they are trying to log into site....

    How could I decrypt such password on login page (from mysql table) to have successful logining?

    or something like

    if(md5($submitted_pw) == $pw_in_db)
    // logged in
    else
    // invalid


    any sugesstions?


    p.s
    $query = "INSERT INTO user VALUES ('DummyUser',md5('DummyPassword'))";

    And then for matching the password use:

    $password = md5($password);
    $query = "SELECT * FROM user WHERE username='DummyUser' AND password='DummyPassword'";


    not working bur when I copy/paste md5 pass from database i CAN log in

    even

    $sql = "SELECT * FROM tablename WHERE username = '$username' AND password='md5($password)' LIMIT 0,1";

    not working
    Last edited by guard; Jul 1, 2004 at 11:05.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •