Help with php code please

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
chris707
Forum Newbie
Posts: 5
Joined: Sat Jul 23, 2011 10:08 am

Help with php code please

Post by chris707 »

Hi i'm having problems with this php code its coming up with an error message sayin that line 7 is a problem.
<?
/* Check User Script */
session_start(); // Start Session

include 'db.php';
// Conver to simple variables
$username = mysql_real_escape_string($_POST['username'];
$password = mysql_real_escape_string($_POST['password'];

if((!$username) || (!$password)){
echo "Please enter ALL of the information! <br />";
include 'login_form.html';
exit();
}

// Convert password to md5 hash
$password = md5($password);

// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);

if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
}
// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('referred_by');
$_SESSION['referred_by'] = $referred_by;
session_register('referral_code');
$_SESSION['referral_code'] = $referral_code;
session_register('partypoker_username');
$_SESSION['partypoker_username'] = $partypoker_username;
session_register('special_user');
$_SESSION['user_level'] = $user_level;

mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");

header("Location: login_success.php");
}
} else {
echo "You could not be logged in! Either the username and password do not match or you have not validated your membership!<br />
Please try again!<br />";
include 'login_form.html';
}
?>


Can anyone help me please and tell me what i've done wrong. Thanks
User avatar
phazorRise
Forum Contributor
Posts: 134
Joined: Mon Dec 27, 2010 7:58 am

Re: Help with php code please

Post by phazorRise »

closing brackets missing in -

Code: Select all

$username = mysql_real_escape_string($_POST['username'];
$password = mysql_real_escape_string($_POST['password'];
corrected-

Code: Select all

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
chris707
Forum Newbie
Posts: 5
Joined: Sat Jul 23, 2011 10:08 am

Re: Help with php code please

Post by chris707 »

Hi i changed that but now it comes up with

You could not be logged in! Either the username and password do not match or you have not validated your membership!
Please try again!

Why wont it log in. I used the correct info to log in.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Help with php code please

Post by Celauran »

$login_check is clearly evaluating to 0. Have you run the query manually? Does that work?
User avatar
phazorRise
Forum Contributor
Posts: 134
Joined: Mon Dec 27, 2010 7:58 am

Re: Help with php code please

Post by phazorRise »

No of rows returned are 0 so control goes into else statement. Check details, both database and what you enter .
1.Does password stored in database is md5 hashed?
2.Does user exist?
3.Does user is activated?

Wrap your code into PHP Code button.
chris707
Forum Newbie
Posts: 5
Joined: Sat Jul 23, 2011 10:08 am

Re: Help with php code please

Post by chris707 »

$login_check is clearly evaluating to 0. Have you run the query manually? Does that work?

How do i run it manually what would i need to change ?


No of rows returned are 0 so control goes into else statement. Check details, both database and what you enter .
1.Does password stored in database is md5 hashed?
2.Does user exist?
3.Does user is activated?

User exists and user is activated. Not sure how i find out if password is md5 hashed. Its just a nomral passwork i created ?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Help with php code please

Post by Celauran »

chris707 wrote:How do i run it manually what would i need to change ?
Either from the MySQL command line, or through PHPMyAdmin.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Help with php code please

Post by flying_circus »

Hi Chris,

Here are some constructive criticisms :)
  • To maximize compatibility, do not use php short tags, it’s best practice to use the full “<?php” tag.
  • Before you try to access the $_POST variable, you need to first make sure they exist. If they don’t exist, it is best practice to set them to a standard value, something like “”, 0, or false.
  • You should validate your input. Screen the data to make sure the user has not entered invalid characters, that the data meets the minimum length requirements and does not exceed maximum length requirement, otherwise it may become truncated
  • Always use the new mysqli database extension. The “I” on the end of mysqli stands for “improve”. No really, it’s the better way to go.
  • Escaping your data is the absolute last step before insertion into a sql query. Don’t manipulate it in any way after it has been escaped, else you may be setting yourself up for sql injection in the future.
  • Md5() is no longer a suitable hash algorithm for hashing passwords, I would steer clear of sha1 as well. I prefer sha512, but sha256 is perfectly acceptable, at this time of writing.
  • You should salt and pepper your password hashes. The salt should be kept with the password (on the database), where the pepper should be kept on another medium (like the file system). This way if one or the other is compromised, there is still hope. You should generate the salt when you create the user account.
  • It is not necessary to use session_register(), in fact, it has become deprecated as of PHP 5.3. Discontinue its use and just set the $_SESSION variable.
  • When Redirecting a user using a header, ALWAYS call exit() immediately afterwards to halt script execution. Simply calling header() does not stop the script.
  • Take a look at how I check the number of returned users. The way it was before, if you somehow accidentally had a duplicate (non-unique) user name, you may get conflicting information. Also note that with the way it was, if the first user passed the username/password check, they would end up with the second users information.

Code: Select all

<?php /* Check User Script */
  # Definitions
    define('PASSWORD_HASH_PEPPER', 'replace_this_with_your_own_strong_random');
    
  # Start Session
    session_start();
    
  # Check Variable Existence before Referencing Them
    $username = isset($_POST['username']) ? $_POST['username']: '';
    $password = isset($_POST['password']) ? $_POST['password']: '';

  # Validate Username & Password
    if(!empty($username) && !empty($password)) {
    # Connect to the database
      $database = new mysqli('my_server', 'my_username', 'my_password', 'my_database');
      
    # Fetch Users with matching username
      $users = $database->query(sprintf("SELECT * FROM `users` WHERE `username`='%s' AND `activated`='1';",
                                        $database->real_escape_string($username)));
                                        
    # Count Results, expecting 1 username match
      if($users->num_rows == 1) {
      # Fetch User Information
        $user = $users->fetch_assoc();
        
      # Check User Password matches supplied password - Rebuild Password Hash
        if($user['password'] == hash('sha256', $password . PASSWORD_HASH_PEPPER . $user['salt'] . $username . $user['id'])) {
        # Set Session Data
          $_SESSION['first_name'] = $user['first_name'];
          $_SESSION['last_name'] = $user['last_name'];
          $_SESSION['email_address'] = $user['email_address'];
          $_SESSION['referred_by'] = $user['referred_by'];
          $_SESSION['referral_code'] = $user['referral_code'];
          $_SESSION['partypoker_username'] = $user['partypoker_username'];
          $_SESSION['user_level'] = $user['user_level'];
          
        # Update timestamp
          $database->query(sprintf("UPDATE `users` SET `last_login`='%d' WHERE `userid`='%d';",
                                   $database->real_escape_string(time()),
                                   $database->real_escape_string($user['id'])));
                                   
        # Redirect to account home
          header("Location: login_success.php");
          exit();
        }
      } else {
      # User Query result count is either less than or greater than 1
        echo "You could not be logged in! Either the username and password do not match or you have not validated your membership! Please try again!";
      }
    } else {
    # Missing information from login form
      echo "Please enter ALL of the information!";
    }
    
  # Include Login Form
    include 'login_form.html';
?>
User avatar
phazorRise
Forum Contributor
Posts: 134
Joined: Mon Dec 27, 2010 7:58 am

Re: Help with php code please

Post by phazorRise »

Here are some constructive criticisms
Absolutely!

login/authentication systems are toughest to build ! :wink:
Post Reply