#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    11
    Rep Power
    0

    Log in tutorials


    firstly my apologies if (when) this post breaks the forum rules.....
    secondly, yes I have used google and the forum search but I'm not 100% sure what I'm looking for.

    I am looking for a log in tutorial (using PHP/MySQL) that is aimed at the n00b (with a basic knowledge of php), that gives code examples (they don't have to be production examples) but more importantly explains what each part does, in effect teaching me instead of just doing it for me.

    A registration system is not really needed because it will be for a small closed community so that can easily be done manually.

    The reason for being logged in to this site would be to have a private section for discussion and the ability to upload photos etc to a public part of the site. (the tut need not cover this)

    Everything I have found so far is either dated, unsuitable or doesn't offer decent explanations of what is being done.

    does anyone know of a good place to look for such a tut?
  2. #2
  3. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,907
    Rep Power
    6351
    I do not know of a place for this kind of information, so I wrote one for you. Completely untested. Tell me if it's confusing or it doesn't work for you.

    PHP Code:
    <?php

    /* DATABASE TABLES

    For this example, a database table called 'users' is required, with the fields:
    id (unsigned int, auto-increment, primary key)
    username (varchar 128 not null, UNIQUE index on this column)
    password (varchar 128 not null)
    loginCount (unsigned int, not null default 0) 
    createDate (DateTime, not null)
    lastLogin (DateTime)

    You may seed this table with:
    INSERT INTO users (username, password) VALUES ('testUser', 'abJnggxhB/yWI');

    The password for this user is 'password!'
    */


    //begin the session:
    session_start();


    //initialize the database connection.  FILL IN YOUR CONNECTION INFORMATION
    mysql_connect('host','user','pass');
    mysql_select_db('db');

    //initialize an empty "error" variable so you don't get a PHP warning later when you try to use it:
    $error '';

    //if $_POST['submit'] is set, that means the user attempted to log in:
    if ( isset($_POST['submit']) ) {
      
    //the form was submitted, but make sure the username and password aren't blank:
      
    if ( empty( $_POST['user'] ) || empty( $_POST['pass'] ) ) {
        
    $error 'Please fill out a username and password';
      } else {
        
    /*username and password are set, attempt to see if the user exists and the login is correct.
          we do this by simply selecting from the table where the username and password match the inputs.
          Note two things:
          1)  We are using crypt() with a salt to determine the password.  Your registration form should 
              create the user's initial password with the SAME METHOD.  YOU MUST USE THIS METHOD TO CREATE USERS
          2)  We wrap all plaintext user input (the username in this case) with mysql_real_escape_string.
              This prevents SQL injection attacks.
        */
        
    $sql "SELECT id, loginCount, lastLogin FROM users WHERE username = '" mysql_real_escape_string($_POST['user']) . "' AND password = '" .
               
    crypt($_POST['pass'], 'abc123SomeSalt321cba') . "'";
        
    //now execute the SQL query and store the results to a variable:
        
    $rs mysql_query$sql );
        
        
    //if $rs is false, we encountered an error.  My query is soundly written, but error handling is ALWAYS a good idea
        
    if ( $rs === false ) { 
          
    //It is always a good idea to write a custom error handler that will handle your errors, email you the problem,
          //log the problem to the filesystem, and show the user a GENERIC non-specific "oops" page.  For a beginner, 
          //simply dying with the error is enough for you, but NEVER do this in production, it reveals your database structure
          
    die("An unexpected error occurred!<br />" mysql_error() . "<br />For the query:<br />" $sql);
        }
        
    //$rs is not false, but did it return a row...?
        
    elseif ( mysql_num_rows$rs ) == ) {
          
    //no rows returned, either the user doesn't exist or their password is bad.  DO NOT TELL THEM which condition occurred.
          //If you make an error that says "that user is ok, but the password is wrong" people can build a list of your users.
          
    $error 'Invalid username/password combination, please try again.';
        } else {
          
    //If we've arrived here, the query was valid and returned a row:
          
    $row mysql_fetch_array($rs);
          
    $_SESSION['loggedIn'] = true;
          
    $_SESSION['userId'] = $row['id'];
          
    $_SESSION['username'] = $_POST['user'];
          
    $_SESSION['loginCount'] = $row['loginCount'];
          
    $_SESSION['lastLogin'] = $row['lastLogin'];
          
    //never store the password anywhere.
          
          //update the two bits of metadata on the user page.  This is not really necessary for a basic login system,
          //but it's fun and cool and gives you a good idea of how to do such things:
          
    mysql_query("UPDATE users SET loginCount = loginCount+1, lastLogin = NOW() WHERE userId = {$row['id']}");
          
    //no error handling here.  Should you write some?  What should it do?  Left up to the reader.
          
          //redirect the user to a "thank you for logging in" page, or to the member page, or whatever:
          
    header("Location: someFile.php");
          die(); 
    //always die after a header call, always
        
    }
      }
    } else {
      
    //$_POST['submit'] is not set, so the form is not submitted.  simply print the form:
      
    ?>
      <!-- if no form action is set, it will post to the same page, which is what we want -->
      <form method="POST">
        <table cellpadding=5>
          <tr>
            <!-- This row contains a single cell that spans two columns and will show the PHP error if there is one. -->
            <th colspan="2">
              <span style="font-weight: bold; color: red;"><?php echo $error?></span>
            </th>
          </tr>
          <tr>
            <td>Username</td>
            <!-- The PHP syntax you see here is called the ternary operator.  It's a one-line IF-THEN check, in the format:
            condition ? if-true : if-false;  You check a condition (our isset check), and if it's true, you use the value
            from if-true.  If the condition is false, you use the if-false value.  In this way we can say "if $_POST['user']
            is set, use it as the value for this cell, otherwise use nothing." -->
            <td><input type="text" name="user" value="<?php echo isset($_POST['user']) ? $_POST['user'] : ""?>" /></td>
          </tr>
          <tr>
            <td>Password</td>
            <td><input type="password" name="pass" value="" /></td>
          </tr>
          <tr>
            <th colspan="2"><input type="submit" name="submit" /></th>
          </tr>
        </table>
      </form>
      
      <?php
      
    //close the bracket for the last "else" in the PHP
    }


    /*Further notes/usage examples.  THE FOLLOWING IS NOT PART OF THIS SCRIPT*/

    //Any page which uses login information (all of them, hopefully) needs this line:
    session_start();
    //This line is necessary to access the session, which is where we stored the login information.
    //It's a good idea to simply put session_start at the top of your general includes.php or whatever.

    //To check to see if a user is logged in to a page:
    if ( isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true ) {
      
    //the user is logged in
    }

    //You may continue to manipulate the session in any way you see fit, but note that it's super-global.  
    //If you overwrite userId or clear the session or destroy the sesion cookie, they will be logged out.
    //They will also be logged out when they close their browser window.
    And read the new user guide.

    -Dan

    Comments on this post

    • LiveTheDead agrees
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2011
    Posts
    11
    Rep Power
    0
    thanks Dan thats a great help. Due to unforeseen circumstances I don't have much free time at the moment but as soon as I do I will give that a test and let you know how I get on with it
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    4
    Rep Power
    0
    Well written, and simple. I really appreciate that you introduced some secruity giving me a place to start researching as that was my next on my list. I'm having a problem with the script that I cannot figure out though. I've fiddle with it but can't seem to come up with anything.

    Somethings wrong with the first bit of code, $rs isn't get a value for somereason. I have the rest of the code commented out as I figured out where the problem was occuring but I'm getting nothing returned, not even an error. Alas I have no idea what's wrong.

    edit: Guh, the code block thing on this forum takes away all the formatting, I fixed the part thats wrong to be readle, I have the rest commented out at anyway.

    edit2: read your post, here we go. hehe.
    php Code:
     
    <?php
    	session_start();
    	//error_reporting(E_ALL);
    	require_once 'app_config.php';
     
    	$error = "";
     
    	if (isset($_POST['submit'])) {
    		if (empty($_POST['user']) || empty($_POST['pass'])) {
    			$error =  'Please fill out a username and password';
    		}	else {
    				$sql = "SELECT id, loginCount, lastLogin FROM users WHERE username = '"
    				.mysql_real_escape_string($_POST['user']) . "' AND password = '" .
    				crypt($_POST['pass'], 'abc123SomeSalt321cba'). "'";
     
    				echo $sql;
     
    				$rs = mysql_query($sql);
    				echo $rs;
    			}
    		}
     
    	/*			
    	if ($rs === false) {
    		die("An unexpected error occured!<br />" . mysql_error() . "<br />For the query:<br />" . $sql);
    	}	elseif (mysql_num_rows($rs) == 0) {
    			$error = 'Invalid username/password, please try again.';
    		} else {
    			$row = mysql_fecth_array($rs);
    			$_SESSION['loggedIn'] = true;
    			$_SESSION['userID'] = $row['id'];
    			$_SESSION['username'] = $_POST['user'];
    			$_SESSION['loginCount']= $row['loginCount'];
    			$_SESSION['lastLogin'] = $row['lastLogin'];
     
    			$sql_metadata = mysql_query("UPDATE users SET loginCount = loginCount+1, lastLogin = NOW()
    			WHERE userId = {row['id']}");
     
    			if ($sql_metadata == false) {
    				die("An unexpected error occured" . mysql_error() . "for the query" .$sql_metadata);
    			}
     
    			header("Location: poll.php");
    			die();
    		}
    		*/
    ?>


    html Code:
    <html>
     <head>
      <link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
     </head>
     
     <body>
      <div id="header"><h1>Login</h1></div>
      <div id="example">test</div>
     
     <div id="content">
      <p>Login:</p>
      <form action="scripts/sessions.php" method="POST">
       <fieldset>
      <label for="user">User Name:</label>
      <input type="text" name="user" size="20"/><br />
      <label for="pass">Password</label>:</label>
      <input type="text" name="pass" size="20"/><br />
     </fieldset>
    <br />
    <fieldset class="center">
      <input type="submit" value="Login"/>
    </fieldset>
    </form>
    </div>
     
    <div id="footer"></div>
    </body>
    </html>
  8. #5
  9. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,907
    Rep Power
    6351
    Welcome to the forum. Please re-post your code by pasting it into the big box, then highlighting it and clicking the "PHP" button. The way you've done it now forces it all on the same line and I cannot read any of it.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    4
    Rep Power
    0
    Originally Posted by ManiacDan
    Welcome to the forum. Please re-post your code by pasting it into the big box, then highlighting it and clicking the "PHP" button. The way you've done it now forces it all on the same line and I cannot read any of it.
    Thanks for the welcome and directing me here from phpfreaks. The code is now formatted.
  12. #7
  13. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,907
    Rep Power
    6351
    You're not getting anything at all?

    1) Does this app_config include file connect to the database properly? Is that wrapped in error handling?

    2) Are you POSTing to this page? None of this code will execute if the POST variables mentioned are empty.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    4
    Rep Power
    0
    Originally Posted by ManiacDan
    You're not getting anything at all?

    1) Does this app_config include file connect to the database properly? Is that wrapped in error handling?

    2) Are you POSTing to this page? None of this code will execute if the POST variables mentioned are empty.
    Nothing :/.

    Yeah, I've used that script for connection with all my others. I posted the HTML just to be sure but yes.

    php Code:
    <?php
    // Database Connection Constants
     
    	define("DB_HOST", "");  //these are filled in on actual script
    	define("DB_USERNAME", "");
    	define("DB_PASSWORD", "");
    	define("DB_NAME", "");
     
    	//connection
     
    	mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)
    		or  die("<p>Error connecting to database: "
    			. mysql_error() . "</p>");
     
    	mysql_select_db(DB_NAME)
    		or die("<p>Error selecting" . DB_NAME . mysql_error() ."</p>");
     
    	//debug mode
    	//$debug_mode = true;
    	//
    	//if ($debug_mode) {
    	//	error_reporting(E_ALL);
    	//}else{
    	//	error_reporting(0);
    	//}
     
    	//function debug_print($message) {
    	//	if ($debug_mode) {
    	//	echo $message;
    	//}
     
    ?>
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    4
    Rep Power
    0
    I got it working like this:

    I'd still like to know what's wrong with the original script, it's bugging me.

    php Code:
    <?php
    	session_start();
    	require_once 'app_config.php';
     
    	$name = mysql_real_escape_string($_POST['user']);
    	$password = mysql_real_escape_string($_POST['pass']);
    	$sql = "SELECT id, loginCount, lastLogin FROM users WHERE username = '" . $name .
    	"' AND password = '" . $password . "';";
    	$login_resource = mysql_query($sql);
     
    	if (!$login_resource) {
    		$error = "an unexpected error occured" . mysql_error();
    		echo $error;
    	}	if (mysql_fetch_row($login_resource) == 0) {
    			echo "username or password is incorrect";
    		}	else {
    				$session_values = mysql_fetch_array($login_resource);
    				$_SESSION['user_id'] = $session_values['id'];
    				$_SESSION['user_name'] = $session_values['username'];
    				$_SESSION['login_count'] = $session_values['loginCount'];
    				$_SESSION['last_login'] = $session_values['lastLogin'];
     
    				header("Location: session2.php");
    				die();
    			}
    ?>

IMN logo majestic logo threadwatch logo seochat tools logo