Jump to content

PHP login Script, with MySQL database... ERROR


djscousey

Recommended Posts

Hi all,

i have recently been looking at a few tutorials, and have thrown together a login/registration script for my "members only" section of my site.

I have a file which i #include  in all of my pages, for the database connection, but it doesnt seem to be doing what is intended of it!

the file layout is :
<?php

define('DATABASE_HOST', 'localhost');
define('DATABASE_USER', 'username');
define('DATABASE_PASSWORD', 'password');
define('DATABASE_TABLESPACE', 'scousemi_scousem');
define('DATABASE_TABLE_PREFIX', 'users_');

?>

but i get the following errors when it is accessing the register.php file

Warning: mysql_query() [function.mysql-query]: Access denied for user 'scousemi'@'localhost' (using password: NO) in /home/scousemi/public_html/members/register.php on line 48

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/scousemi/public_html/members/register.php on line 48

Warning: mysql_query() [function.mysql-query]: Access denied for user 'scousemi'@'localhost' (using password: NO) in /home/scousemi/public_html/members/register.php on line 50

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/scousemi/public_html/members/register.php on line 50

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/scousemi/public_html/members/register.php on line 52

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/scousemi/public_html/members/register.php on line 53

Warning: mysql_query() [function.mysql-query]: Access denied for user 'scousemi'@'localhost' (using password: NO) in /home/scousemi/public_html/members/register.php on line 103

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/scousemi/public_html/members/register.php on line 103
Access denied for user 'scousemi'@'localhost' (using password: NO)


here is a copy of the script that i have in the register.php file:

<?

include 'db.php';

// Define post fields into simple variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_address = $_POST['email_address'];
$username = $_POST['username'];
$info = $_POST['info'];

/* Let's strip some slashes in case the user entered
any escaped characters. */

$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email_address = stripslashes($email_address);
$username = stripslashes($username);
$info = stripslashes($info);


/* Do some error checking on the form posted fields */

if((!$first_name) || (!$last_name) || (!$email_address) || (!$username)){
    echo 'You did not submit the following required information! <br />';
    if(!$first_name){
        echo "First Name is a required field. Please enter it below.<br />";
    }
    if(!$last_name){
        echo "Last Name is a required field. Please enter it below.<br />";
    }
    if(!$email_address){
        echo "Email Address is a required field. Please enter it below.<br />";
    }
    if(!$username){
        echo "Desired Username is a required field. Please enter it below.<br />";
    }
    include 'signup.php'; // Show the form again!
    /* End the error checking and if everything is ok, we'll move on to
    creating the user account */
    exit(); // if the error checking has failed, we'll exit the script!
}
   
/* Let's do some checking and ensure that the user's email address or username
does not exist in the database */

$sql_email_check = mysql_query("SELECT email_address FROM users
            WHERE email_address='$email_address'");
$sql_username_check = mysql_query("SELECT username FROM users
            WHERE username='$username'");

$email_check = mysql_num_rows($sql_email_check);
$username_check = mysql_num_rows($sql_username_check);

if(($email_check > 0) || ($username_check > 0)){
    echo "Please fix the following errors: <br />";
    if($email_check > 0){
        echo "<strong>Your email address has already been used by another member
        in our database. Please submit a different Email address!<br />";
        unset($email_address);
    }
    if($username_check > 0){
        echo "The username you have selected has already been used by another member
          in our database. Please choose a different Username!<br />";
        unset($username);
    }
    include 'signup.html'; // Show the form again!
    exit();  // exit the script so that we do not create this account!
}

/* Everything has passed both error checks that we have done.
It's time to create the account! */

/* Random Password generator.
http://www.phpfreaks.com/quickcode/Random_Password_Generator/56.php

We'll generate a random password for the
user and encrypt it, email it and then enter it into the db.
*/

function makeRandomPassword() {
  $salt = "abchefghjkmnpqrstuvwxyz0123456789";
  srand((double)microtime()*1000000);
      $i = 0;
      while ($i <= 7) {
            $num = rand() % 33;
            $tmp = substr($salt, $num, 1);
            $pass = $pass . $tmp;
            $i++;
      }
      return $pass;
}

$random_password = makeRandomPassword();

$db_password = md5($random_password);

// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users (first_name, last_name,
        email_address, username, password, info, signup_date)
        VALUES('$first_name', '$last_name', '$email_address',
        '$username', '$db_password', '$info2', now())")
        or die (mysql_error());

if(!$sql){
    echo 'There has been an error creating your account. Please contact the webmaster.';
} else {
    $userid = mysql_insert_id();
    // Let's mail the user!
    $subject = "Your Membership at Members Only!";
    $message = "Dear $first_name $last_name,
    Thank you for registering at our website, http://www.scousemike.co.uk!
   
    Your nearly at the point of gaining access to the members area, all you have to do is Activate your membership:
   
    http://www.scousemike.co.uk/activate.php?id=$userid&code=$db_password
   
    Once you activate your memebership, you will be able to login
    with the following information:
    Username: $username
    Password: $random_password
   
    Thanks!
    The Webmaster
   
    This is an automated response, please do not reply!";
   
    mail($email_address, $subject, $message,
        "From: MyDomain Webmaster<[email protected]>\n
        X-Mailer: PHP/" . phpversion());
    echo 'Your membership information has been mailed to your email address!
    Please check it and follow the directions!';
}

?>

Any ideas why i am getting them errors?  they are the correct login credentials... :S:S


one frustrated user!!
Try adding this to your db.php file...

[code]
<?php

$connection = mysql_connect("localhost",
                            "username", 
                            "password");
mysql_select_db("dbName", $connection); //edit this to be your actual database name

?>
[/code]
=] =] =] much appreciated gmwebs.... thats worked marvelously....

just got another slight hitch now >-[

i have registered myself on the database, for administrative purposes, but when i try to log in, it says that either my username and/or password is incorrect, or i havent activated my account.

But i have activated them, and the username and password are what it states in the e-mail i received :S



if you wish to check it out its located at


www.scousemike.co.uk/members/signup.php   


its all looking scratchy at the moment as i am still in the "creation" part of it all

any help will be greatly appreciated
My guess is that you are encrypting the password before storing it in the DB, but then you are not encrypting the form's password input field to see whether it matches what you have in the DB when the user logs on. They will submit their password in unencrypted text remember. Post your login code here, as I said, it's only a guess ;)
ok, i have worked out that section now, but i will post the code anyway, to see if you can spot any direct issues with the code:

<?
/* Check User Script */

include 'db.php';

$username = $_POST['username'];
$password = $_POST['password'];

if((!$username) || (!$password)){
    echo "Please complete ALL fields! <br />";
    include 'login.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('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 "Unfortunately we have been unable to log you in, this maybe because 1) your username and/or password is incorrect; 2) you haven't yet activated your details!<br />
    Please try again!<br />";
    include 'login.html';
}
?>

thanks
Try this in the login script, just to double check the query used... Compare the value of the password in the $sql output with what is in your DB.

[code]
<?php
/* Check User Script */

include 'db.php';

$username = $_POST['username'];
$password = $_POST['password'];

if((!$username) || (!$password)){
    echo "Please complete ALL fields!
";
    include 'login.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('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 "Unfortunately we have been unable to log you in, this maybe because 1) your username and/or password is incorrect; 2) you haven't yet activated your details! Please try again!";
echo "<br />";
echo "The SQL query is : " . $sql; //use just for debugging
exit(); //exit to see the output
    include 'login.html';
}
?>
[/code]
that works perfectly gmwebs.... your a great help.....


i will leave you with one more request/issue should you wish to help me with it :-P


how would i go about putting a form on there for users to be able to change there password to something they can easily remember? because the 8 alphanumeric passwords it randomly generate, are a bit of a mind bender to remember.....


thanks in advance for all your help
So what was wrong in the end?

Try this for a change password form...

[code]
<?php
session_start(); // we must never forget to start the session

switch($_POST['option']){
    default:
    //Do something if the option value is not posted
    break;
   
    case "changepass":
changePass($_POST['new_pass'], $_POST['confirm_pass']);
break;
}

function changePass($new_pass, $confirm_pass){

if ((!$_POST['new_pass']) || (!$_POST['confirm_pass']) || ($_POST['new_pass'] !== $_POST['confirm_pass'])) {

$username = $_SESSION['user_name'];

    // quick check to see if record exists   
    $sql_check = mysql_query("SELECT password FROM users WHERE username='$username'");
    $sql_check_num = mysql_num_rows($sql_check);

    if($sql_check_num == 0){
        Redirect("../error.php?error=norecord");
        exit();
    }
    // Everything looks ok, generate password, update it and send it!
   
    $db_password = md5($new_pass);
   
    $sql = mysql_query("UPDATE users SET password='$db_password'
                WHERE username='$username'");
   
$email_address = $_SESSION['email_address'];
    $subject = "Password changed!";
    $message = "Your password has been changed successfully.
   
    New Password: $new_pass
   
    Thanks!
    The Webmaster
   
    This is an automated response, please do not reply!";
   
    mail($email_address, $subject, $message, "From: Webmaster<[email protected]>\n
        X-Mailer: PHP/" . phpversion());
   
// if the user is logged in, unset the session
if (isset($_SESSION['basic_is_logged_in'])) {
  unset($_SESSION['basic_is_logged_in']);
}
}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<title>Change Password </title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<link rel="stylesheet" href="css/site.css" type="text/css" />
</head>
<body>

<form method="post">
<input type="hidden" name="option" value="changepass">

<label for="new_pass">New Password: </label><input type="text" name="new_pass"></input>
<label for="confirm_pass">Confirm: </label><input type="text" name="confirm_pass"></input>
<input type="submit" value="change password">
</form>

</body>
</html>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.