Jump to content

Recommended Posts

 

I'm trying to build a registration form. I have the form completed and everything. The action of the form is currently on _Server['PHP_Self'] so I can view if the script is working without actually inserting anything in a database. I currently new to PHP, so I can't understand everything on why it's not working properly.

 

I have 6 input fields , for the user to put in. Here is the code I currently have. The problem I'm having is I have this certain line in the code

 if ( eregi('^[[:alnum:]\.\'\-]$', stripslashes($name) ) ) 

to check for openspaces or anyother character. Now I have it saying that if it is true, echo a line, so I can see it is currently working. The problem is even is there is only letter in it, it still does the 'else' function. I don't understand why.

 

here's the PHP code.

 

<?php 


if( array_key_exists('register', $_POST))
	{

$name 		= trim($_POST['name']);
....
$reg		= $_POST['register'];

	if ( !empty($name) && !empty($lastn) && !empty($username) && !empty($pass) && !empty($pass2) && !empty($email)) 

			{	

		 if ( eregi('^[[:alnum:]\.\'\-]$', stripslashes($name) ) ) 

					{

					echo "Insert into Database Now";


					}

						else {

								echo("Only Letters and Numbers are allowed");

								}

		echo "<p>Name:	$name </p>";
		....
		echo "<p>Sex:$sex </p>";	


	}

	else {

	echo "Every Fields must be Filled in!" ; 

	}

 }


?>

 

 

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/
Share on other sites

You will often find that form validation is easier when using a white-list approach, or building your validation around the choices that are allowed (rather than trying to think of everything that is not allowed).

 

<?php
// Flag form as having errors:
$has_errors = false;

// Let's say we want $_POST['fld'] to only contain alphanumeric
$regexp = '/^[a-zA-Z0-9]+$/'; // Matches one or more alphanumeric characters
if(!preg_match($regexp, $_POST['fld'])){
  echo "Error: Field has invalid data!";
  $has_errors = true;
}

// Do the same for some other fields
// ...

// Now we can process the input
if($has_errors){
  // Re-display the form with error messages
}else{
  // No errors, we can process
  echo "Processing!";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-247606
Share on other sites

Forms usually have three required functions:

 

  • ShowForm() - Show the initial form to the user, also used to re-display a form that has errors.
  • ValidateForm() - Validate the form input, returns true if valid form, false if invalid form
  • ProcessForm() - Does the form processing and then displays final output or performs redirection

 

Lastly, I like to include a Show() function for the form that wraps up the logic.

<?php
function Show(){
  $html = "";
  // Called by the client, shows the form
  if(ValidateForm()){
    // Form is valid, so we process
    $html = ProcessForm();
  }else{
    // Form is invalid, so we show it
    $html = ShowForm();
  }
  return $html;
}
?>

 

ShowForm

<?php
function ShowForm(){
  global $form_errors;
  $html = ""; // Start off empty
  if(is_array($form_errors) && count($form_errors)){
    // Form had errors, so we are redisplaying
    $html .= "The follow errors were encountered:<ul><li>"
             . implode("</li><li>", $form_errors) . "</li></ul>";
  }
  // Now build the form
  $html .= "Field 1"
            . "Field 2";
  return $html;
}
?>

 

ValidateForm

<?php
function ValidateForm(){
  global $form_errors;
  $has_errors = false;
  $form_errors = Array();

  // If the form has not been submitted, it is obviously invalid
  if(count($_POST) == 0){
    return false; // This will cause ShowForm() to be called from our Show() function
  }

  // A form has been submitted, so we can validate each field.

  // Check valid username
  $regexp = '/^[a-zA-Z0-9]+$/'; // Usernames are alphanumeric
  if(!preg_match($regexp, $_POST["username"])){
    $has_errors = true;
    $form_errors[] = "Valid user names are alphanumeric.";
  }

  // Check for a password
  if(strlen(trim($_POST['pass'])) == 0){
    $has_errors = true;
    $form_errors[] = "You must specify a password.";
  }

  // Check that both password fields match
  if(strcmp($_POST['pass'], $_POST['pass_confirm'])){
    $has_errors = true;
    $form_errors[] = "Your password fields do not match.";
  }

  // And so on...

  return !$has_errors;  // Negative logic
}
?>

 

ProcessForm

<?php
function ProcessForm(){
  $html = ""; // start empty

  // We must sanitize our form input.  I prefer to put everything into a $Clean array, which signals
  // to me that it has been explicitly cleaned.  It also leaves the variables as $raw to use them
  // elsewhere
  $Clean = Array();
  $Clean['Username'] = mysql_real_escape_string($_POST['username']);
  $Clean['Password'] = mysql_real_escape_string($_POST['pass']);

  // Build our query, I opt not to use sprintf
  $sql = "INSERT INTO users (username, pass) VALUES ("
         . "{$Clean['Username']}, {$Clean['Password']} "
         . ")";
  $q = mysql_query($sql);
  if( query_was_valid ){
    header("Location: " . REDIRECT_SUCCESS_URL);
    exit();
  }else{
    $html = "There was an error processing your request.";
  }
  return $html;
}
?>

 

If your entire form is contained in my_form.php, it can be used like this:

<?php
require_once("my_form.php");
echo Show();
?>

 

This should give you some good ideas on how to work / deal with forms.  I've simplified it a bit and there are some clever enhancements you can make, such as turning it into a class.

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-247637
Share on other sites

Tnx for the help...I was stuck on this form thing. I'll work on it later tonight, i'll post more questions if I get stuck. I don't quite (sp?) understand the class object thing. I read the chapter from my book a few times, but I don't understand it fully yet.

What if there was a address form. What would

be the syntax that will allow whitespaces.

 

 

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-247657
Share on other sites

Tnx for the help...I was stuck on this form thing. I'll work on it later tonight, i'll post more questions if I get stuck. I don't quite (sp?) understand the class object thing. I read the chapter from my book a few times, but I don't understand it fully yet.

What if there was a address form. What would

be the syntax that will allow whitespaces.

 

 

 

What is the name of the book?

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-247664
Share on other sites

Is there no Edit button? Mine only shows the qoute button.

 

Ok, I have it showing, I'm getting how to display the form, but not I ran into trouble. In my form I use a php function to display a dropdown menu, atleast in 4 places. Since it's easier to diplay with php than by hand. How do I put that into the $html string?Is it even possible?

 

 

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248358
Share on other sites

<?php
function createSel(){
  $html = "<select>"
           . "<option>1</option>"
           . "<option>2</option>"
           . "</select>";
  return $html;
}

function ShowForm(){
  global $form_errors;
  $html = ""; // Start off empty
  if(is_array($form_errors) && count($form_errors)){
    // Form had errors, so we are redisplaying
    $html .= "The follow errors were encountered:<ul><li>"
             . implode("</li><li>", $form_errors) . "</li></ul>";
  }
  // Now build the form
  $html .= "Field 1"
            . "Field 2"
            . createSel(); // <-------- Add the selection
  return $html;
}
?>

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248364
Share on other sites

Is there anyway I could use something like this

 

   <select name="year">
   
      <?php 

$y = range(2000, 1930);

for( $i=0; $i < count($y); $i++)
 {
 	$value = $y[$i];

	echo "<option value='$value'> $value </option>";	

		}
?>
    
   </select>

 

Instead of having to write every single option, by itself?

 

damn, I feel like a dumbass heh,

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248384
Share on other sites

Ok, thanks for your help, its working now.

I have another question though, how would I go about validating the form though?

or calling the ValidateForm(), inside the "action='' "

 

I tried


<form action=".ValidateForm()." >
&
<form action="ValidateForm()"> 

 

but, none work...

I'll go to more reading...since I seem to know not 2 much.

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248464
Share on other sites

You leave the action attribute set as $_SERVER['PHP_SELF']; the script that outputs the form is the same script that processes it.

 

As the final step in form processing you can redirect to another page, or even the same script again, to prevent the problem of a duplicate form submittal when a user refreshes the page.

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248540
Share on other sites

I have the code like this

 

 <form id=\"reg\" action=\"<?php echo $_SERVER[\'PHP_SELF\'];?>\" method=\"post\" name=\"regform\" >

 

but I get this error

 

Parse error: parse error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\s\reg.php on line 108

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248555
Share on other sites

<form id="reg" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="regform" >

 

Why are you escaping the quotes in html?

 

Because the html is in a php string, look at the code in the previous replies.

 

You have an unneeded backslash after PHP_SELF.

 

Removed it, but still have the same problem...

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248574
Share on other sites

<form id="reg" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="regform" >

 

Why are you escaping the quotes in html?

 

Because the html is in a php string, look at the code in the previous replies.

 

You have an unneeded backslash after PHP_SELF.

 

Removed it, but still have the same problem...

 

If that is true than the <?php echo is not needed. Try this:

 

<?php
$string = "<form id=\"reg\" action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\" name=\"regform\" >";

 

That is how it should be done if it is part of a string.

 

 

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248582
Share on other sites

We'll need to see more code, both above and below the offending line.

 

If you're going to do:

<?php
$string = "<form id=\"reg\" action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\" name=\"regform\" >";
?>

 

You might as well go all the way and eliminate the dot operator:

<?php
$string = "<form id=\"reg\" action=\"{$_SERVER['PHP_SELF']}\" method=\"post\" name=\"regform\" >";
?>

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248583
Share on other sites

=) I have pretty good reasons to keep the . operators there. One of which is because it is easier to point out variables. It sucks looking through code to find the $ or the { } to see where variables are. Much easier to look at it with a . $var . =)

 

Second is that the { } takes up more processing time and is less efficient. I am unsure of how much, maybe I will create a test and see if it is true, but yea.

 

Either will work just fine.

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248586
Share on other sites

Hey guys thanks for all your help  :). The form is working in basic steps now, for the processform, I currently just made another function that echos the field for now..So I can take baby steps and learn from this. You know, I plan on working with php more, so I want to learn everything carefully.

 

I'm using the

. $_Server['PHP_SELF'];

 

since i'm working with dreamweaver, and it colors the different codes types, which makes it easier for me right now. I'm only using dreamweaver for the color coding though...lol

 

If I get stuck anywhere I'll ask more questions...

 

Link to comment
https://forums.phpfreaks.com/topic/50411-form-processing/#findComment-248679
Share on other sites

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.