Code Snippet

Home » Code Snippets » PHP » Login Function

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();

Subscribe to The Thread

  1. kneep

    // 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. Thanks Chris,

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

  3. 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.

    • Dyllon

      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.

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

  5. 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.

    • Sankar

      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.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~