Login Function

These functions will log in a user based on a username and password being matched in a MySQL database.

// function to escape data and strip tags
function safestrip($string){
       $string = strip_tags($string);
       $string = mysql_real_escape_string($string);
       return $string;
}

//function to show any messages
function messages() {
   $message = '';
   if($_SESSION['success'] != '') {
       $message = '<span class="success" id="message">'.$_SESSION['success'].'</span>';
       $_SESSION['success'] = '';
   }
   if($_SESSION['error'] != '') {
       $message = '<span class="error" id="message">'.$_SESSION['error'].'</span>';
       $_SESSION['error'] = '';
   }
   return $message;
}

// log user in function
function login($username, $password){

 //call safestrip function
 $user = safestrip($username);
 $pass = safestrip($password);

 //convert password to md5
 $pass = md5($pass);

  // check if the user id and password combination exist in database
  $sql = mysql_query("SELECT * FROM table WHERE username = '$user' AND password = '$pass'")or die(mysql_error());

  //if match is equal to 1 there is a match
  if (mysql_num_rows($sql) == 1) {

                          //set session
                          $_SESSION['authorized'] = true;

                          // reload the page
                         $_SESSION['success'] = 'Login Successful';
                         header('Location: ./index.php');
                         exit;


   } else {
               // login failed save error to a session
               $_SESSION['error'] = 'Sorry, wrong username or password';
  }
}

Usage

Values would be captured from a form and then passed to the main function:

login($username, $password);

All pages involved would have the messages function somewhere so proper use feedback is given:

messages();

Comments

  1. User Avatar
    kneep
    Permalink to comment#

    // log user in function
    function login($username, $password){

    //call safestrip function
    $user = safestrip($user);
    $pass = safestrip($pass);

    first you use the full $username and $password variables, then you use short version of them…this will not work this way

  2. User Avatar
    Leon
    Permalink to comment#

    Thanks Chris,

    i find your site very informative and a lot of good stuff that i learn from you

  3. User Avatar
    Tom

    Hey Chris

    Love the site – quick question about this snippet.

    I had some issues with this, the sql query wouldn’t grab my username and or password until i moved…

    //convert password to md5
    $pass = md5($pass);

    below the query snippet

    im new to md5 function and im not sure if what i did was correct but its the only way it seems to be running correctly.

    • User Avatar
      Dyllon
      Permalink to comment#

      That just means your passwords in your database aren’t hashed.

      md5 gives your string of text an irreversible 32 character hash code.

      example:
      md5(‘hi’)
      would come out to be:
      49f68a5c8493ec2c0bf489821c21fc3b

      it’s very useful for if anyone should get into your database, they won’t know the passwords of all of the users.

    • User Avatar
      Magictallguy
      Permalink to comment#

      @Dyllon
      Rainbow tables – MD5 is regarded as one of the worst encryption methods currently used.
      I’d recommend crypt()

      Here’s a function I’ve used for years (and no-one else has even come close to cracking it!)

      function mtgCrypt($pass) {
          return crypt($pass, '$6$rounds=5000$aZXCeqsdGEADfubAFSDBUIegdvbuiEG8432$');
      }
      

      Change the “aZXCeqsdGEADfubAFSDBUIegdvbuiEG8432” to whatever you want – as long as it does NOT dynamically change (for example, using rand() functions to generate a string) – it’s gotta stay the same ;)

  4. User Avatar
    Martin
    Permalink to comment#

    If you don’t initialize the sessions calling a session_start() your session variables will always get by the false option…

  5. User Avatar
    Feras
    Permalink to comment#

    Hey, I was curious, If i was to use this, Do i need to paste it on every page that has to have a log in?
    How do i make multiple pages where you need to log in from?
    Email me your answer please. Thank you.

    • User Avatar
      Sankar
      Permalink to comment#

      Hi all,

      I too searching for the same .. Why can’t you guys create a code for full login modules and post here. So that most of the people can use it.
      Waiting for response. Atleast via E-mail.

      Thanks,
      Sankar.

  6. User Avatar
    ND
    Permalink to comment#

    Hello Chris,

    can I use this Login-function in WordPress too ?
    Which modifications should I use if required ?
    Is there an Video or Artikel about enduser-login, registration with wordpress ?

    Greetings

    Andy

  7. User Avatar
    Marius de Beer
    Permalink to comment#

    I would steer clear from using MD5 hashes as it is no longer considered secure.

  8. User Avatar
    Michael Hanon

    This was posted a long time ago and should be removed. There are a lot of issues here. Not hiding the SessionID from javascript, not regenerating and destroying the session, mysql_real_escape_string is not secure, MD5 is decryptable and the password is not salted. If you’re looking for a pretty secure login script let me know. I would be happy to raise awareness.

  9. User Avatar
    jay
    Permalink to comment#

    i’m just wondering, where would i going to put this codes? or how to save this one

  10. User Avatar
    Ivan K.
    Permalink to comment#

    good is md5, but hash ripemd128 is so much fine

    hash(‘ripemd128’, $pass);

  11. User Avatar
    Joe Coder
    Permalink to comment#

    This code is obsolete and insecure. It should be immediately removed.

    Nobody should be using this code!

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag