Beginner...can't get registration code to work. Please help.

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
groc426
Forum Newbie
Posts: 16
Joined: Tue Oct 28, 2008 4:44 pm

Beginner...can't get registration code to work. Please help.

Post by groc426 »

I'm simply trying to set-up a registration and login page for my web site. Any help would be greatly appreciated! These forms are being called by my index page and placed in my content section of my wireframe. I keep getting the errors on my registration page:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/content/g/r/o/groc42683/html/php/registration.php:11) in /home/content/g/r/o/groc42683/html/includes/reg_form.inc.php on line 5

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/g/r/o/groc42683/html/php/registration.php:11) in /home/content/g/r/o/groc42683/html/includes/reg_form.inc.php on line 5


The Web Sites:
http://www.moultonlava.com/php/registration
http://www.moultonlava.com/login/login

Registration Code

Code: Select all

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/connections/con_clients.php');?>
<?php
//Prevent incursion attack
if (!isset($_SESSION)) {
session_start();
}
//Check for session, if false create it
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
    $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue):
mysql_escape_string($theValue);
    switch ($theType) {
    case "text":
        $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
        break;
    case "long":
    case "int":
        $theValue = ($theValue != "") ? intval($theValue) : "NULL";
        break;
    case "double":
        $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
        break;
    case "date":
        $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
        break;
    case "defined":
        $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
        break;
}
return $theValue;
}
}
//This sets up a call to this page
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
    $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
 
// Begin the Server-Side Checks ---------------------------------------------
 
//Create an empty array to hold any error messages
$error = array();
 
//Set an insert flag to see if the form has been submitted look at the bottom of the form and you should
//find a hidden field with the value "MM_insert"
$MM_flag="MM_insert";
if (isset($_POST[$MM_flag])) {
 
    // check that there are values in the name fields of the form
    if (empty($_POST['cfirst']) || empty($_POST['clast'])) {
        $error['name'] = 'Please enter both first name and last name';
        }
    // Set a flag that assumes the password is OK
    $pwdOK = true;
    
    // trim any leading and trailing white space - Note: ˆ have the user enter the password twice,     in two
    // separate fields. I only store the password from the first field
    $_POST['cpassword1'] = trim($_POST['cpassword1']);
 
    // if the password is less than 6 characters, create alert and set flag to false
    if (strlen($_POST['cpassword1']) < 6) {
        $error['pwd_length'] = 'Your password must be at least 6 characters';
        $pwdOK = false;
        }
    // if passwords do not match, create alert and set flag to false
 
if ($_POST['cpassword1'] != trim($_POST['cpassword2'])) {
$error['pwd'] = 'Your passwords don\'t match';
$pwdOK = false;
}
// if password OK, encrypt it to a 40 character string hash - Your database password field
// must be varchar and at least 40 characters in size
 
if ($pwdOK) {
    $_POST['cpassword1'] = sha1($_POST['cpassword1']);
    }
// validate the proper form of the email address using a regular expression
$checkEmail = '/^[^@]+@[^\s\r\n\'";,@%]+$/';
if (!preg_match($checkEmail, trim($_POST['cemail']))) {
    $error['email'] = 'Please enter a valid email address';
    }
    
// Check the length of the email address to insure that it is at least 6 characters - x@x.xx
    $_POST['cemail'] = trim($_POST['cemail']);
    $loginUsername = $_POST['cemail'];
    if (strlen($loginUsername) < 6) {
        $error['length'] = 'Please select a username that contains at least 6 characters';
        }
        
// check that the email address doesn't already exist in the database
$LoginRS__query = sprintf("SELECT c_email FROM c_register_info WHERE c_email=%s", GetSQLValueString($loginUsername,
"text"));
mysql_select_db($database_con_clients, $con_clients);
$LoginRS=mysql_query($LoginRS__query, $con_clients) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
//if there is a row in the database, the username was found - cannot add the requested username
// VERY IMPORTANT - note that the text string is in double quotes so the value of $loginUsername
// can be shown, NOT just the variable name
if($loginFoundUser){
$error['username'] = "$loginUsername is already in use. Please choose a different username (email address).";
}
//Addition server-side checks would be added here to validate other fields in the form
 
} // This closes the whole check portion that began with testing to see if the form had been submitted
 
//If there are no errors, then insert the record
if (!$error) { //This line has been added to surround the regular dreamweaver insert code
 
// Determines if the form has been submitted
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmreg")) {
 
// Populate the session
$_SESSION['clientfirst'] = $_REQUEST['cfirst'];
$_SESSION['clientlast'] = $_REQUEST['clast'];
    $insertSQL = sprintf("INSERT INTO c_register_info (c_last, c_first, c_password1, c_email, c_areacode, c_phone, c_ext, c_address, c_city, c_state, c_postal, c_join) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                        GetSQLValueString($_POST['clast'], "text"),
                        GetSQLValueString($_POST['cfirst'], "text"),
                        GetSQLValueString($_POST['cpassword1'], "text"),
                        GetSQLValueString($_POST['cemail'], "text"),
                        GetSQLValueString($_POST['careacode'], "text"),
                        GetSQLValueString($_POST['cphone'], "text"),
                        GetSQLValueString($_POST['cext'], "text"),
                        GetSQLValueString($_POST['caddress'], "text"),
                        GetSQLValueString($_POST['ccity'], "text"),
                        GetSQLValueString($_POST['cstate'], "text"),
                        GetSQLValueString($_POST['cpostal'], "text"),
                        GetSQLValueString($_POST['joined'], "text"));
    
    mysql_select_db($database_con_clients, $con_clients);
    $Result1 = mysql_query($insertSQL, $con_clients) or die(mysql_error());
    
    $insertGoTo = "http://www.moulonglava.com/index.php";
    if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
    }
    header(sprintf("Location: %s", $insertGoTo));
    
} // This ends the surround that submits the record if there are no server-side validation errors
 
    //If the record has been inserted to the database, clear the $_POST array
    $_POST = array();
}
?>
<div class="post">
<h2>Registration Form</h2>
<?php
// This displays the error array if it is not empty, if it is empty the user sees only the regular code
// if there are errors, each error is displayed in its own list item
if ($error) {
echo '<ul class="warning">';
foreach ($error as $alert) {
echo "<li>$alert</li>\n";
}
echo '</ul>';
}
?>
<p>All fields marked with an asterisk (*) are required.</p>
<form action="<?php echo $editFormAction; ?>" method="post" name="frmreg" id="frmreg"
onsubmit="MM_validateForm('cfirst','','R','clast','','R','cemail','','RisEmail','cpassword1','','R','cpassword2','','R'
,'chint','','R','canswer','','R','careacode','','RisNum','cphone','','R');return document.MM_returnValue">
<fieldset>
<legend>Identification and Login Information</legend>
<label for="cfirst">*First name: </label>
<input type="text" name="cfirst" id="cfirst" tabindex="1" size="10" />
<br />
<label for="clast">*Last name: </label>
<input type="text" name="clast" id="clast" tabindex="2" size="15"/>
<br />
<label for="cemail">*Email: </label>
<input type="text" name="cemail" id="cemail" size="30" tabindex="3"  />
(This will be your user name)<br />
<label for="cpassword1">*Password: </label>
<input type="password" name="cpassword1" id="cpassword1" tabindex="4" /> (must be at least 6
characters)
<br />
<label for="cpassword2">*Password: </label>
<input type="password" name="cpassword2" id="cpassword2" tabindex="5" onBlur="checkPassword();"
/>
(Please retype the password)<br />
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="caddress">Address: </label>
<input type="text" name="caddress" id="caddress" size="40" tabindex="11" class="notreq" />
<br />
<label for="ccity">City: </label>
<input type="text" name="ccity" id="ccity" size="20" tabindex="13" class="notreq" />
<br />
<label for="cstate">State:</label>
<select name="cstate" size="1" id="cstate" tabindex="14" title="State Postal Abbreviations" class="notreq">
<option selected="selected">Select a State or Province</option>
<option value="AB">Alberta</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="BC">British Columbia</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticutt</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MB">Manitoba</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NB">New Brunswick</option>
<option value="NE">Nebraska</option>
<option value="NL">Newfoundland and Labrador</option>
<option value="NT">Northwest Territories</option>
<option value="NS">Nova Scotia</option>
<option value="NU">Nunavut</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="ON">Ontario</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="PE">Prince Edward Island</option>
<option value="QC">Quebec</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="SK">Saskatchewan</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming </option>
<option value="YT">Yukon</option>
</select>
<br />
<label for="cpostal">Zip\Postal:</label>
<input type="text" name="cpostal" id="cpostal" size="10" tabindex="15" class="notreq"/>
<br />
<label for="careacode" title="Phone number beginning with the area Code">Phone:</label>
(&nbsp;
<input type="text" name="careacode" id="careacode" size="3" tabindex="17" class="notreq"/>
&nbsp;)&nbsp;
<label for="cphone" title="Phone number" style="float:none; padding:0;">&nbsp;</label>
<input type="text" name="cphone" id="cphone" size="8" tabindex="18" class="notreq"/>
<span>Ext.</span>
<label for="cext" title="Extension" style="float:none; padding:0;">&nbsp;</label>
<input type="text" name="cext" id="cext" size="5" tabindex="19" class="notreq"/>
<br />
<label for="cregister" title="Click the Register button to complete the registration process">&nbsp;</label>
<input type="submit" name="submit" id="cregister" value="Register" tabindex="20" />
<input type="hidden" name="MM_insert" value="frmreg" />
<?php
//This will create a date for the joined field below
ini_set('date.timezone', 'America/Boise');
$time = date('Y-m-d');
?>
<input type="hidden" name="joined" value="<?php echo $time; ?>" />
</fieldset>
</form>
</div>
 
Login Code:

Code: Select all

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/connections/con_clients.php');?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}
 
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
 
if (isset($_POST['cemail'])) {
  $loginUsername=$_POST['cemail'];
  $password=$_POST['cpassword'];
  $MM_fldUserAuthorization = "c_level";
  $MM_redirectLoginSuccess = "/login/succeed.php";
  $MM_redirectLoginFailed = "/login/login.php";
  $MM_redirecttoReferrer = true;
  mysql_select_db($database_con_clients, $con_clients);
    
  $LoginRS__query=sprintf("SELECT c_email, c_password1, c_level FROM c_register_info WHERE c_email=%s AND c_password1=%s",
  GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
   
  $LoginRS = mysql_query($LoginRS__query, $con_clients) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
    
    $loginStrGroup  = mysql_result($LoginRS,0,'c_level');
    
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;       
 
    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];  
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>
<?php
//set knownuser flag, by default is is false, but if a cookie is present that was set when a user
// registered, then the flag is changed and the values are retrieved from the cookie
$user = false;
if ($_COOKIE['client']){
$user = true;
$userfirst = $_COOKIE['client']['firstname'];
$userlast = $_COOKIE['client']['lastname'];
$usersname = $userfirst." ".$userlast;
}
?>
<?php
// This code is shown only if the known user flag is true. It displays a login form so the user can login
if ($user) {
echo "<h3>Welcome $usersname</h3>";
echo '<form action="" method="post" name="frmlogin" style="font-size:smaller">';
echo '<fieldset>';
echo '<label for="uname">Username:</label><input type="text" id="uname" size="15" /><br />';
echo '<label for="pswd">Password:</label><input type="password" id="pswd" size="10" /><br />';
echo '<label for="login"&nbsp;</label><input type="submit" id="submit" value="Login" /><br />';
echo '<a href="/clients/restore.php" title="Login help page link">Forgot Login Information</a>';
echo '</fieldset>';
echo '</form>';
}?>
<div class="post">
<?php
// This displays the error array if it is not empty, if it is empty the user sees only the regular code
// if there are errors, each error is displayed in its own list item
if ($error) {
echo '<ul class="warning">';
foreach ($error as $alert) {
echo "<li>$alert</li>\n";
}
echo '</ul>';
}
?>
<form action="<?php echo $loginFormAction; ?>" method="POST" name="frmreg" id="frmreg"
onsubmit="MM_validateForm('cfirst','','R','clast','','R','cemail','','RisEmail','cpassword1','','R','cpassword2','','R'
,'chint','','R','canswer','','R','careacode','','RisNum','cphone','','R');return document.MM_returnValue">
<fieldset>
<legend>Login</legend>
<label for="cemail">Username: </label>
<input type="text" name="cemail" id="cemail" tabindex="1" size="30" />
<br />
<label for="cpassword1">Password:</label>
<input type="password" name="cpassword" id="cpassword" tabindex="2" size="15"/>
<br />
<label for="clogin" title="Click the Login button to complete the login process">&nbsp;</label>
<input type="submit" name="submit" id="clogin" value="Login" tabindex="3" />
<input type="hidden" name="MM_insert" value="frmreg" />
</fieldset>
</form>
</div>
groc426
Forum Newbie
Posts: 16
Joined: Tue Oct 28, 2008 4:44 pm

Re: Beginner...can't get registration code to work. Please help.

Post by groc426 »

Code to lengthy?

:banghead:
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: Beginner...can't get registration code to work. Please help.

Post by aceconcepts »

You should declare session_start() at the top of the page.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Beginner...can't get registration code to work. Please help.

Post by califdon »

Probably the include file on the first line sends something (even a blank space character) to the browser before the session_start().
groc426
Forum Newbie
Posts: 16
Joined: Tue Oct 28, 2008 4:44 pm

Re: Beginner...can't get registration code to work. Please help.

Post by groc426 »

aceconcepts-
Thanks. I've done just that. Removed the session starter to where the code was being called from. Fixed the problem, but now a new one appears.
Warning: Cannot modify header information - headers already sent by (output started at /home/content/g/r/o/groc42683/html/php/registration.php:16) in /home/content/g/r/o/groc42683/html/includes/reg_form.inc.php on line 137
Line 137 entails:

Code: Select all

    $insertGoTo = "http://www.moultonlava.com/index.php";
    if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
    }
    [b]header(sprintf("Location: %s", $insertGoTo));[/b]
 
So after successful registration I would like it to return back to the home page, so I'm not certain where to place this header, or what I should modify. Advice? Thanks! After this I should hopefully have a fully working registration page :mrgreen:
groc426
Forum Newbie
Posts: 16
Joined: Tue Oct 28, 2008 4:44 pm

Re: Beginner...can't get registration code to work. Please help.

Post by groc426 »

Not sure if this would help also...but here is where the registration form is being called from:

Code: Select all

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/connections/con_clients.php');?>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!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">
<head>
    <meta http-equiv="Content-Type"
          content="text/html; charset=us-ascii" />
    <link href="/css/styles.css"
          rel="stylesheet"
          type="text/css" />
    <script type="text/javascript"
          src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en">
    //<![CDATA[
    //]]>
    </script>
    <script src="/java/menu1.js"
          type="text/javascript">
    //<![CDATA[
    //]]>
    </script>
    <script src="/java/opacity.js"
          type="text/javascript">
    //<![CDATA[
        
    //]]>
    </script>
 
    <title>moultonlava.com registration</title>
</head>
 
<body class="moulton">
<div id="container">
<div id="header">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/header.inc.php');?>
</div>
 
<div id="navigation">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/navigation.inc.php');?>
</div>
 
<div id="sidebar">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/sidebar.inc.php');?>
</div>
 
<div id="registerlink">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/registerlink.inc.php');?>
</div>
 
<div id="content">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/reg_form.inc.php');?>
</div>
<div id="clearfloat"></div>
 
<div id="footer">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/footer.inc.php');?>
</div>
    </div>
</body>
</html>
 
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Beginner...can't get registration code to work. Please help.

Post by onion2k »

When you do this...

Code: Select all

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/connections/con_clients.php');?>
<?php
... it means you're including con_clients.php, then sending a carriage return to the user, and then doing some more PHP. Anything in the second block that tries to send a header (eg the call to session_start() ) will be broken. You don't need to exit the PHP block at all...

Code: Select all

<?php
 
  require_once($_SERVER['DOCUMENT_ROOT'].'/connections/con_clients.php');
 
  if (!isset($_SESSION)) {
  //rest of the script..
 
groc426
Forum Newbie
Posts: 16
Joined: Tue Oct 28, 2008 4:44 pm

Re: Beginner...can't get registration code to work. Please help.

Post by groc426 »

Thanks onion2k!-
I was going through my code and realized that right before I read your post. Didn't make any sense. Changed it. Of course I'm still not certain where to post the header that will return the user back to the home page after successful registration.

*Note I have actually found a way around this by placing ob_start() at the very beginning of the code. This ensure that no output is being sent before the header (as i understand it). This is great, but I'm attempting to learn PHP and this seems like a lazy way of getting it to work. So I will still persist with my question; where do I place the header (assuming I did not use ob_start())? :D
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Beginner...can't get registration code to work. Please help.

Post by califdon »

There are several ways to redirect the browser to a new location, and I'm not sure that I know which is the best one to use in each possible scenario, but one fact is this: whenever you use PHP's header() function, it absolutely MUST be the very first thing that is sent to the browser. If your script as much as hiccups towards the browser before you send a header(), you will receive that error. There are situations where you can use ob_start() and ob_end_flush(). I haven't found that necessary in my own scripts, so I can't advise you on using that. It is possible to use javascript, having a js function that you can call, that does a window.location() call. What I normally do is structure my php script so that the decision whether or not to redirect will be done before any output is sent to the browser, including not calling include files, etc. Then I can issue a header() call, if appropriate.
Post Reply