Jump to content

Recommended Posts

I've only modified the code below for the query, I just removed that to make it shorter, the query works fine. I've added human verification to the script and it displays the image and numbers fine, I also echo'd out the variables and they match using SHA1(). My captcha script is displaying the image properly and sets the $_SESSION['pass_phrase'] variable fine.

 

It isn't throwing any errors or creating the account.

 

As of right now I have a headache and figured I could use some help here. Let me know if you spot the error.

 

<?php
  error_reporting(E_ALL);
  require_once('cons.php');
   // Get the variable sent by AJAX script if it is typed in
  // Connect to the database
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_REQUEST['username'])) {
$ok = 'okay';
$den = 'denied';

   // Secure the information
$passname = mysqli_real_escape_string($dbc, trim($_REQUEST['username']));
   // Lookup the username in the database
      $query = "SELECT username FROM info WHERE username = '$passname'";
      $data = mysqli_query($dbc, $query);
   // Allow some time to get the response
 sleep(3);
   // If 1 is returned that name exsists, if 0 then we can move forward
      if (mysqli_num_rows($data) == 0) {
   // Send okay back to the ajax script so it knows to stop bothering the user
echo $ok;
return $ok;
} else {
   // Send denied back to the ajax script so the user knows that name is taken
echo $den;
return $den;
} // Close If / Else statement
  } // Close (isset($_REQUEST['username'])) {

  // Start of Main Submit Function Script
   session_start();
  require_once('aprs.php');

  if (isset($_POST['submit'])) {
    // Grab the profile data from the POST and secure it

    $avatar = mysqli_real_escape_string($dbc, trim($_POST['avatar']));
    $usern = mysqli_real_escape_string($dbc, trim($_POST['username1']));
    $password1 = mysqli_real_escape_string($dbc, trim($_POST['password1']));
    $password2 = mysqli_real_escape_string($dbc, trim($_POST['password2']));
    $email = mysqli_real_escape_string($dbc, trim($_POST['email']));
    $side = mysqli_real_escape_string($dbc, trim($_POST['side']));
    $class = mysqli_real_escape_string($dbc, trim($_POST['class']));
    $vercap = mysqli_real_escape_string($dbc, trim($_POST['verify']));

// convert username to all lowercase

$userna = strtolower($usern);
$username = stripslashes($userna);

// Check the CAPTCHA pass-phrase for verification
$phrase = SHA1($vercap);
if ($_SESSION['pass_phrase'] == $phrase) {

// Expression for validating the username is properly formatted.
if (preg_match('/[^0-9A-Za-z]/',$username)) {  

// Expression for validating the e-mail is properly formatted.
if (preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)){  

// Check to make sure all the form fields are filled in 
if (!empty($avatar) && !empty($username1) && !empty($password1) && !empty($password2) && ($password1 == $password2) && !empty($email) && !empty($side) && !empty($class)) {

// If all the fields are filled in correctly then we can check the username to see if it's registered
// Make sure someone isn't already registered using this username
      $query = "SELECT * FROM info WHERE username = '$username'";
      $data = mysqli_query($dbc, $query);
      if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$hash = md5( rand(0,1000) );
        $query = "INSERT INTO";
        mysqli_query($dbc, $query);

// Confirm success with the user
 echo '<div id="signconf">';
        echo '<p>Your new account has been successfully created. Please check your Email for the final verification.';
 echo '</div>';

// Send the registration e-mail so the user can activate thier account
$to = $email; // Send email to our user
$subject = 'Signup | Verification'; // Give the email a subject
$message = '

Thanks for signing up!
Your account has been created, you can login with the following credentials after you have activated your account by clicking the url below.

------------------------
Username: '.$username.'
Password: '.$password1.'
------------------------

Please click this link to activate your account:

http://www.mydomain.com/verify.php?email='.$email.'&hash='.$hash.'

'; // Our message above including the link

$headers = 'From:me@mydomain.com' . "\r\n"; // Set from headers
mail($to, $subject, $message, $headers); // Send our email

       mysqli_close($dbc);
       exit();

// If there was an issue with the username already taken, display an error
} else {
 echo '<div id="signconf">';
        echo '<p class="error">An account already exists for this username. Please use a different address.</p>';
 echo '</div>';
        $username = "";
} // End the if(mysqli_num_rows($data) == 0) { check
// If there was an issue with the user not filling in the form correctly we post an error
} else {
echo '<div id="signconf">';
       echo '<p class="error">You must enter all of the sign-up data, including the desired password twice.</p>';
echo '</div>';
} // End the if(mysqli_num_rows($data) == 0) { check
// If there was an error with the e-mail address entered we need to post an error
} else {
echo '<div id="signconf">';
echo 'The email you have entered is invalid, please try again.';  
echo '</div>';
} // End the if(mysqli_num_rows($data) == 0) { check
// If there was an error with the format of the username we need to post an error
} else {
echo '<div id="signconf">';
echo 'The email you have entered is invalid, please try again.';  
echo '</div>';
} // End the if(mysqli_num_rows($data) == 0) { check
// If there was an error with the captcha not matching we post an error
} else {
 echo '<div id="signconf">';   
        echo "The verification text didn't match the picture.";
 echo '</div>';
} // End else for Captcha check
}  // End the if(mysqli_num_rows($data) == 0) { check

// Connection to the database is no longer needed so we can close it
mysqli_close($dbc);

// We no longer need php so let's close that and start the submit form
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Registration</title>
<link type="text/css" rel="stylesheet" href="tlstyle.css" />
<script src="scripts/utils.js" type ="text/javascript"></script>
<script src="scripts/validation.js" type="text/javascript"></script>
</head>
<body>
<div id="csignup">
<div id="signform"> 
<p>Please enter all the information below to sign up.</p>
  <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
     <label for="username1">Username:</label>
     <input type="text" id="username1" name="username1" value="<?php if (!empty($username1)) echo $username; ?>" maxlength = "7" /><br />
     <label>Password:</label>
     <input type="password" id="password1" name="password1" value="<?php if (!empty($password1)) echo $password1; ?>" class="jcinput"/><br />
     <label>Password (retype):</label>
     <input type="password" id="password2" name="password2" value="<?php if (!empty($password2)) echo $password2; ?>" class="jcinput"/><br />
     <label>E-Mail Address:</label>
     <input type="text" id="email" name="email" value="<?php if (!empty($email)) echo $email; ?>" class="jcinput"/><br />
     <label for="verify">Verification:</label>
     <img src="captcha.php" alt="Verification" /><br />
     <label for="verify">Verification:</label>
     <input type="text" id="verify" name="verify" class="jcinput" /><br />
     <label>Choose Your Avatar:</label>
<input type="radio" name="avatar" value="/images/smile.png" /> <img src="/images/smile.png" alt="1" />
<input type="radio" name="avatar" value="/mages/smile.png" /> <img src="/images/smile.png" alt="1" />
<input type="radio" name="avatar" value="/mages/smile.png" /> <img src="/images/smile.png" alt="1" />
<input type="radio" name="avatar" value="/images/smile.png" /> <img src="/images/smile.png" alt="1" /><br />
     <label>Choose Your Side:</label>
<input type="radio" name="side" value="A" />A
<input type="radio" name="side" value="B" />B
<div id="signclassb">
<div id="signclass">
Choose a Class:
<ul><li><input type="radio" name="class" value="A" /> A</li>
<li><input type="radio" name="class" value="B" /> B</li>
<li><input type="radio" name="class" value="C" /> C</li></ul>
</div>
</div>
    <input type="submit" value="Sign Up" name="register" class="signsub" />
  </form>

</div>
</div>
</body> 
</html>

Link to comment
https://forums.phpfreaks.com/topic/210564-need-help-with-registration-script/
Share on other sites

The part I think is the problem is:

// The username is unique, so insert the data into the database
$hash = md5( rand(0,1000) );
        $query = "INSERT INTO";
        mysqli_query($dbc, $query);

 

More specifically,

$query = "INSERT INTO";
        mysqli_query($dbc, $query);

 

I think you need to add more to your query than "INSERT INTO".  MySQL is like a woman, it wants you to spell it out word for word.

If you don't post the actual code responsible for the symptom, no one can help you with your actual code.

 

LOL -

  // Allow some time to get the response

sleep(3);

 

^^^ Computer programs don't work that way. All that does is make it take longer for the code on the page to execute.

I've posted all the code that is relevant to the problem.

 

The only thing that may be causing a further issue is the captcha script I'll post that below.

 

Outside of that the query isn't the issue, prior to adding the CAPTCHA check and the AJAX code everything worked just fine. The query doesn't need any information from either of the new additions.

 

<?php
  session_start();

  // Set some important CAPTCHA constants
  define('CAPTCHA_NUMCHARS', 6);  // number of characters in pass-phrase
  define('CAPTCHA_WIDTH', 115);   // width of image
  define('CAPTCHA_HEIGHT', 25);   // height of image

  // Generate the random pass-phrase
  $pass_phrase = "";
  for ($i = 0; $i < CAPTCHA_NUMCHARS; $i++) {
    $pass_phrase .= chr(rand(97, 122)); 
}

  // Store the encrypted pass-phrase in a session variable
  $_SESSION['pass_phrase'] = SHA1($pass_phrase);

  // Create the image  
  $img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);  

  // Set a white background with black text and gray graphics  
  $bg_color = imagecolorallocate($img, 255, 255, 255);     
  // white  
  $text_color = imagecolorallocate($img, 0, 0, 0);
  // black  
  $graphic_color = imagecolorallocate($img, 64, 64, 64);   
  // dark gray

  // Fill the background
  imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color);
  // Draw some random lines
  for ($i = 0; $i < 5; $i++) {
    imageline($img, 0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color);
  }

  // Sprinkle in some random dots
  for ($i = 0; $i < 50; $i++) {
    imagesetpixel($img, rand() % CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color);
  }

  // Draw the pass-phrase string
  imagettftext($img, 18, 0, 5, CAPTCHA_HEIGHT - 5, $text_color, './DejaVuSans-Bold.ttf', $pass_phrase);

  // Output the image as a PNG using a header  
  header("Content-type: image/png");  imagepng($img);

  // Clean up
  imagedestroy($img);
?>

If you don't post the actual code responsible for the symptom, no one can help you with your actual code.

 

LOL -

  // Allow some time to get the response

sleep(3);

 

^^^ Computer programs don't work that way. All that does is make it take longer for the code on the page to execute.

 

 

Just started out with learning AJAX and the only way I know to pause a script to allow further input on the html form is by doing it with php, if you know how to do it with AJAX I'd be happy to alter it.  8)

I don't see anywhere in this thread where you actually state what does happen when you submit the form? What do you see in front of you?

 

You should be using both of the following settings so that all the php detected errors will be both reported and displayed (actually your development system should have these two settings in your master php.ini so you don't need to put them into your code or remember to remove them later) -

 

ini_set("display_errors", "1");
error_reporting(E_ALL);

 

I also don't see any actual AJAX code involved and you should get your application working first before you attempt to use AJAX with it.

  if (isset($_POST['submit'])) {

 

^^^ Also, there's nothing in the posted code that sets $_POST['submit'] so your form processing code is being skipped over.

 

Did you do any basic debugging of this on your system while you were creating it and before you posted it here?

I did I had error reporting on, I've been writing the script from the ground up as I learn more. It's just gotten so large that I overlooked things and needed help so I came here. So the error reporting wouldn't post anything for that type of mistake. I'll give that a whirl.

Thank you for your assistance I appreciate it.

 

Edit: I noticed your edit and I had my signup form working prior to adding AJAX then tested after adding that and it worked, I added the human verification to it and that's when it screwed up.

 

When I submit the form nothing occurs and the account isn't registered. Also with the adjustments and corrections made to the submit function, and the value missing the " in the form I corrected that.

 

Can you look at the preg_match section and let me know If I did it correctly please?

 

Thanks,

Bill

By looking at your code you've got an odd way that you're doing your error checking...  might i suggest doing your error checking all at once like:

 

if($_SESSION['pass_phrase'] != $phrase) { $e[] = "Pass Phrase doesn't match"; }

 

then when you get all your error checking done like so, to check if there are any errors you simply:

 

if(sizeof($e == 0) {

// everything is good

} else {

// there is at least 1 error

}

 

this makes it easier to debug, and makes it easier to read.

 

A sample of this would be like this, i have the sneaking suspicion i am missing a } somewhere in the code probably right @ the very end.....  You may also want to look and make sure I have all the error checking done...  but doing something like this instead of how you had it would theoretically work a bit better than how you had it coded.

 

<?php
session_start();
error_reporting(E_ALL);
require_once('cons.php');
require_once('aprs.php');
   // Get the variable sent by AJAX script if it is typed in
  // Connect to the database
  
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$_un = isset($_REQUEST['username']) $_REQUEST['username'] : '';
if ($_un != '') {

$ok = 'okay';
$den = 'denied';


   // Secure the information
$passname = mysqli_real_escape_string($dbc, trim($_REQUEST['username']));
   // Lookup the username in the database
    $query = "SELECT username FROM info WHERE username = '$passname'";
    $data = mysqli_query($dbc, $query);
   // Allow some time to get the response
sleep(3);
   // If 1 is returned that name exsists, if 0 then we can move forward
	if (mysqli_num_rows($data) == 0) {
   // Send okay back to the ajax script so it knows to stop bothering the user
		echo $ok;
		return $ok;
	} else {
   // Send denied back to the ajax script so the user knows that name is taken
		echo $den;
		return $den;
	} // Close If / Else statement
  } // Close (isset($_REQUEST['username'])) {

  // Start of Main Submit Function Script


if (isset($_POST['submit'])) {
    // Grab the profile data from the POST and secure it

    $avatar = mysqli_real_escape_string($dbc, trim($_POST['avatar']));
    $usern = mysqli_real_escape_string($dbc, trim($_POST['username1']));
    $password1 = mysqli_real_escape_string($dbc, trim($_POST['password1']));
    $password2 = mysqli_real_escape_string($dbc, trim($_POST['password2']));
    $email = mysqli_real_escape_string($dbc, trim($_POST['email']));
    $side = mysqli_real_escape_string($dbc, trim($_POST['side']));
    $class = mysqli_real_escape_string($dbc, trim($_POST['class']));
    $vercap = mysqli_real_escape_string($dbc, trim($_POST['verify']));

// convert username to all lowercase

$userna = strtolower($usern);
$username = stripslashes($userna);

// Check the CAPTCHA pass-phrase for verification
$phrase = SHA1($vercap);
if ($_SESSION['pass_phrase'] != $phrase) { $e[] = "<div id=\"signconf\">The verification text didn't match the picture.</div>"; }
if(!preg_match('/[^0-9A-Za-z]/', $username)) { $e[] = "<div id=\"signconf\">The email you have entered is invalid, please try again.</div>"; }
if(!preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)) { $e[] = "<div id=\"signconf\">The email you have entered is invalid, please try again.</div>"; }
if(!empty($avatar) && !empty($username1) && !empty($password) && !empty($password2) && ($password1 == $password2) && !empty($email) && !empty($side) && !empty($class)) {
	$query = "SELECT * FROM info WHERE username = '".$username."'";
	$data = mysqli_query($dbc, $query);
	if(mysql_num_rows($data) != 0) {  $e[] = "<div id=\"signconf\">An account already exists for this username. Please use a different address.</div>"; }
} else {
	$e[] = "<div id=\"signconf\">You must enter all of the sign-up data, including the desired password twice.</div>";
}

if(sizeof($e) == 0) {
	// all is good
	$hash = md5(rand(0, 1000) );
	query = "INSERT INTO";
	mysqli_query($dbc, $query));

	 echo '<div id="signconf">';
         echo '<p>Your new account has been successfully created. Please check your Email for the final verification.';
     echo '</div>';
	 // Send the registration e-mail so the user can activate thier account
	$to = $email; // Send email to our user
	$subject = 'Signup | Verification'; // Give the email a subject
	$message = '

Thanks for signing up!
Your account has been created, you can login with the following credentials after you have activated your account by clicking the url below.

------------------------
Username: '.$username.'
Password: '.$password1.'
------------------------

Please click this link to activate your account:

http://www.mydomain.com/verify.php?email='.$email.'&hash='.$hash.'

'; // Our message above including the link

$headers = 'FroM: me@mydomain.com' . "\r\n"; // Set from headers
mail($to, $subject, $message, $headers); // Send our email

       mysqli_close($dbc);
       exit();
} else {
	// all is not so good
	// here you could foreach through all of the error results above..  i think i got em all.
}
// Connection to the database is no longer needed so we can close it
mysqli_close($dbc);

// We no longer need php so let's close that and start the submit form
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Registration</title>
<link type="text/css" rel="stylesheet" href="tlstyle.css" />
<script src="scripts/utils.js" type ="text/javascript"></script>
<script src="scripts/validation.js" type="text/javascript"></script>
</head>
<body>
<div id="csignup">
<div id="signform"> 
<p>Please enter all the information below to sign up.</p>
  <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
     <label for="username1">Username:</label>
     <input type="text" id="username1" name="username1" value="<?php if (!empty($username1)) echo $username; ?>" maxlength = "7" /><br />
     <label>Password:</label>
     <input type="password" id="password1" name="password1" value="<?php if (!empty($password1)) echo $password1; ?>" class="jcinput"/><br />
     <label>Password (retype):</label>
     <input type="password" id="password2" name="password2" value="<?php if (!empty($password2)) echo $password2; ?>" class="jcinput"/><br />
     <label>E-Mail Address:</label>
     <input type="text" id="email" name="email" value="<?php if (!empty($email)) echo $email; ?>" class="jcinput"/><br />
     <label for="verify">Verification:</label>
     <img src="captcha.php" alt="Verification" /><br />
     <label for="verify">Verification:</label>
     <input type="text" id="verify" name="verify" class="jcinput" /><br />
     <label>Choose Your Avatar:</label>
<input type="radio" name="avatar" value="/images/smile.png" /> <img src="/images/smile.png" alt="1" />
<input type="radio" name="avatar" value="/mages/smile.png" /> <img src="/images/smile.png" alt="1" />
<input type="radio" name="avatar" value="/mages/smile.png" /> <img src="/images/smile.png" alt="1" />
<input type="radio" name="avatar" value="/images/smile.png" /> <img src="/images/smile.png" alt="1" /><br />
     <label>Choose Your Side:</label>
<input type="radio" name="side" value="A" />A
<input type="radio" name="side" value="B" />B
<div id="signclassb">
<div id="signclass">
Choose a Class:
<ul><li><input type="radio" name="class" value="A" /> A</li>
<li><input type="radio" name="class" value="B" /> B</li>
<li><input type="radio" name="class" value="C" /> C</li></ul>
</div>
</div>
    <input type="submit" value="Sign Up" name="register" class="signsub" />
  </form>

</div>
</div>
</body> 
</html>

 

as far as checking email, use this function instead

 

function validEmail($email)
{
   $isValid = '1';
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = '0';
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = '0';
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = '0';
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = '0';
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = '0';
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = '0';
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = '0';
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = '0';
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = '0';
      }
   }
   return $isValid;
}

 

usage:

 

$vemail = ValidEmail($_POST['email']);  if($vemail == 0) { // error } else { // success }

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.