PDA

View Full Version : need help with a database error


Pesho
01-27-2006, 11:40 AM
Hi all,
I soon started developing a small web site and now have problems with the User Authentication part. So, I hope you have answers to my questions.

1. As I've never used the mail() function before I'm not sure if I have to configure something. I only changed php.ini writing "SMTP = localhost" and "sendmail_from = p.kalpakliev@iu-bremen.de"

2. I get an error: "ERROR - database error" which comes from the "h_register_funcs.inc" file. I guess MySQL doesn't accept the query and I can't figure out why.
I've manually created a table "user" by typing:
CREATE TABLE user(user_id int not null auto_increment primary key,
user_name varchar(25),
first_name varchar(25),
last_name varchar(25),
password varchar(25),
email varchar(30),
remote_addr varchar(20),
confirm_hash varchar(50),
is_confirmed tinyint,
date_created date);

Probably I've taken some datatypes wrong, I'm not sure.


Here is the code I use(most of it is copied directly from the book and is quite readable):

h_register_funcs.inc:
<?php

//a file with the database host; u.n.; p.; db; md5 encryption seed.
include_once("C:/phpbook/phpbook-vars.inc");

function user_register() {
// This function will only work with superglobal arrays, because
// I'm not passing in any values or declaring globals
global $supersecret_hash_padding;

// Are all vars present and passwords match?
if (strlen($_POST['user_name']) <= 25 && strlen($_POST['password1']) <= 25 && ($_POST['password1'] == $_POST['password2']) && strlen($_POST['email']) <= 50 && validate_email($_POST['email'])) {
// Validate username and password
if (account_namevalid($_POST['user_name']) || strlen($_POST['password1'] >= 6)) {

$user_name = strtolower($_POST['user_name']);
$user_name = trim($user_name);
// Don't need to escape, because single quotes aren't allowed
$email= $_POST['email'];
// Don't allow duplicate usernames or emails
$query = "SELECT user_id
FROM user
WHERE user_name = '$user_name'
OR email = '$email'";
$result = mysqli_query($dbh, $query);
if ($result && mysqli_num_rows($result) > 0) {
$feedback = 'ERROR - Username or email address already exists';
return $feedback;
} else {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = md5($_POST['password1']);
$user_ip = $_SERVER['REMOTE_ADDR'];
// Create a new hash to insert into the db and the confirmation email
$hash = md5($email.$supersecret_hash_padding);

$query = "INSERT INTO user (user_name, first_name, last_name, password, email, remote_addr, confirm_hash, is_confirmed, date_created)
VALUES ('$user_name', '$first_name', '$last_name', '$password', '$email', '$user_ip', '$hash', 0, NOW())";
$result = mysqli_query($dbh, $query);
if (!$result) {
$feedback = 'ERROR - Database error';
return $feedback;
} else {
// Send the confirmation email
$encoded_email = urlencode($_POST['email']);
$mail_body = <<< EOMAILBODY
Thank you for registering at Example.com. Click this link to confirm your registration:

http://localhost/confirm.php?hash=$ha...6;encoded_email

Once you see a confirmation message, you will be logged into Example.com
EOMAILBODY;
mail ($email, 'Example.com Registration Confirmation', $mail_body, 'From: noreply@example.com');

// Give a successful registration message
$feedback = 'YOU HAVE SUCCESSFULLY REGISTERED. You will receive a confirmation email soon';
return $feedback;
}
}
} else {
$feedback = 'ERROR - Username or password is invalid';
return $feedback;
}
} else {
$feedback = 'ERROR - Please fill in all fields correctly';
return $feedback;
}
}


function account_namevalid() {

// must have at least one character
if (strspn($_POST['user_name'],"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-") == 0) {
return false;
}

// must contain all legal characters
if (strspn($_POST['user_name'],"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_") != strlen($_POST['user_name'])) {
return false;
}

// min and max length
if (strlen($_POST['user_name']) < 5) {
return false;
}
if (strlen($_POST['user_name']) > 25) {
return false;
}

// illegal names
if (eregi(& quot;^((root)|(bin)|(daemon)|(adm)|(lp)|(sync)|(shutdown)|(halt)|(mail)|(news)|(
uucp)|(operator)|(games)|(mysqli)|(httpd)|(nobody)|(dummy)|(www)|(cvs)|(shell)|(
ftp)|(irc)|(debian)|(ns)|(download))$", $_POST['user_name'])) {
return false;
}
if (eregi("^(anoncvs_)", $_POST['user_name'])) {
return false;
}

return true;
}


function validate_email($email) {
return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email));
}


function user_confirm() {
// This function will only work with superglobal arrays, because
// I'm not passing in any values or declaring globals
global $supersecret_hash_padding;

// Verify that they didn't tamper with the email address
$new_hash = md5($_GET['email'].$supersecret_hash_padding);
if ($new_hash && ($new_hash == $_GET['hash'])) {
$query = "SELECT user_name
FROM user
WHERE confirm_hash = '$new_hash'";
$result = mysqli_query($dbh, $query);
if (!$result || mysqli_num_rows($result) < 1) {
$feedback = 'ERROR - Hash not found';
return $feedback;
} else {
// Confirm the email and set account to active
$email = $_GET['email'];
$hash = $_GET['hash'];
$query = "UPDATE user SET email='$email', is_confirmed=1 WHERE confirm_hash='$hash'";
$result = mysqli_query($dbh, $query);
return 1;
}
} else {
$feedback = 'ERROR - Values do not match';
return $feedback;
}
}

?>


h_register.php:
<?php

require_once('h_register_funcs.inc');

if ($_POST['submit'] == 'Mail confirmation') {
$feedback = user_register();

// In every case, successful or not, there will be feedback
$feedback_str = "<P class=\"errormess\">$feedback</P>";
} else {
// Show form for the first time
$feedback_str = '';
}


// ----------------
// DISPLAY THE FORM
// ----------------
include_once('h_header_footer.php');
site_header('Registration');

// Superglobals don't work with heredoc
$php_self = $_SERVER['PHP_SELF'];

$reg_str = <<< EOREGSTR
<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0 ALIGN=CENTER WIDTH=621>
<TR>
<TD ROWSPAN=10><IMG WIDTH=15 HEIGHT=1 SRC="spacer.gif"></TD>
<TD WIDTH=606></TD>
</TR>
<TR>
<TD>

$feedback_str
<P CLASS="left"><B>REGISTER</B><BR>
Fill out this form and a confirmation email will be sent to you. Once you click on the link in the email your account will be confirmed and you can begin to contribute to the community.</P>
<FORM ACTION="$php_self" METHOD="POST">
<P CLASS="bold">First Name<BR>
<INPUT TYPE="TEXT" NAME="first_name" VALUE="$first_name" SIZE="20" MAXLENGTH="25"></P>
<P CLASS="bold">Last Name<BR>
<INPUT TYPE="TEXT" NAME="last_name" VALUE="$last_name" SIZE="20" MAXLENGTH="25"></P>
<P CLASS="bold">Username<BR>
<INPUT TYPE="TEXT" NAME="user_name" VALUE="$user_name" SIZE="10" MAXLENGTH="25"></P>
<P CLASS="bold">Password<BR>
<INPUT TYPE="password" NAME="password1" VALUE="" SIZE="10" MAXLENGTH="25"></P>
<P CLASS="left"><B>Password</B> (again)<BR>
<INPUT TYPE="password" NAME="password2" VALUE="" SIZE="10" MAXLENGTH="25"></P>
<P CLASS="left"><B>Email</B> (required for confirmation)<BR>
<INPUT TYPE="TEXT" NAME="email" VALUE="$email" SIZE="30" MAXLENGTH="50">
</P>
<P><INPUT TYPE="SUBMIT" NAME="submit" VALUE="Mail confirmation"></P>
</FORM>

</TD>
</TR>
</TABLE>
EOREGSTR;
echo $reg_str;

site_footer();

?>


h_header_footer.php:
<?php
function site_header($title)
{
$site_header = <<< EOHEADER
<HTML>
<HEAD>
<TITLE>$title</TITLE>
</HEAD>

<BODY>
EOHEADER;
echo $site_header;
}

function site_footer()
{
$site_footer = <<< EOFOOTER
</BODY>
</HTML>
EOFOOTER;
echo $site_footer;
}
?>


h_confirm.php:
<?php

/*****************************************************
* New user confirmation page. Should only get here *
* from an email link. *
*****************************************************/


require_once('h_register_funcs.inc');
include_once('h_header_footer.php');

site_header('Account Confirmation');

if ($_GET['hash'] && $_GET['email']) {
$worked = user_confirm();
} else {
$feedback_str = "<P class=\"errormess\">ERROR - Bad link</P>";
}


if ($worked != 1) {
$noconfirm = '<P class="errormess">Something went wrong. Send email to admin@example.com for help. If you clicked through to this page directly, please go to login.php instead.</P>';
} else {
$confirm = '<P class="big">You are now confirmed. <A HREF="login.php">Log in</A> to start browsing the site</P>';
}

$page = <<< EOPAGE

<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0 ALIGN=CENTER WIDTH=621>
<TR>
<TD><IMG WIDTH=15 HEIGHT=1 SRC=../images/spacer.gif></TD>
<TD WIDTH=606 CLASS=left>
$feedback_str
$noconfirm
$confirm
</TD>
</TR>
</TABLE>
EOPAGE;

echo $page;

site_footer();

?>

arne
01-27-2006, 04:52 PM
i'm sorry, i looked a little but i can't find it right away. Too many codes actually for me to look over it all on a friday ;) BUT you might do some ordinary debugging and set the E_reporting all thingie inside ! That MIGHT (i'm not sure) help. The debugging would be could anyway i gues.

Pesho
01-27-2006, 07:09 PM
I've done a bit of debugging. The error probably comes from this fragment. The thing I can't figure out is why the $feedback which is returned contains only the string "ERROR - database error" and nothing specific connected to .mysqli_error($dbh)

else {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = md5($_POST['password1']);
$user_ip = $_SERVER['REMOTE_ADDR'];
// Create a new hash to insert into the db and the confirmation email
$hash = md5($email.$supersecret_hash_padding);

$query = "INSERT INTO user (user_name, first_name, last_name, password, email, remote_addr, confirm_hash, is_confirmed, date_created)
VALUES ('$user_name', '$first_name', '$last_name', '$password', '$email', '$user_ip', '$hash', 0, NOW())";
$result = mysqli_query($dbh, $query);
if (!$result) {
$feedback = 'ERROR - Database error'.mysqli_error($dbh);
return $feedback;
}

Peter B
01-27-2006, 10:56 PM
SMTP = smtp.your_isp.com insteed of LOCALHOST in php.ini
Unless you have a mail server in your localhoat
Peter.

N_R_D
01-28-2006, 12:06 AM
---------