Jump to content

Form Verification before submitting


studgate

Recommended Posts

Hi Guys, I am trying to verify a couple fields in a

form before it gets submitted, I used javascript but

it still submit the data to the database even after it gives

the warning message. Is there a better way to do that in

php? I have a report_process.php that inserts the data into

the database.

Any help is welcome.

Thanks in advance!

Link to comment
Share on other sites

I have found this example online but it doesn't work for

me, it didn't get me anything. Any help??

<?php /* this is guarunteed to work it is possible to use <? (short tags but this style works everywhere).*/
/*Only verify/validate form when it is submitted program name: form.php */
if(isset($_POST[submit])){
  $error='';//initialize $error to blank
  if(trim($_POST[username])=='' || strlen(trim($_POST[username])) < 6 ||strlen(trim($_POST[username])) >12){
      $error.="Please enter a username between 6 and 12 characters!<br />"; //concatenate the $error Message with a line break
  }
  if(trim($_POST[password])=='' || strlen(trim($_POST[password]))< 6){
      $error.="Your password must be at least 6 characters in length!<br />";//concatenate more to $error  
  }
  if(trim($_POST[email])==''){
    $error.="An email address is required!<br />";
  }
      else {
        if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST[email])) {
        $error="The e-mail you entered was not in the proper format!";
        
        }
    }
  if($error==''){//Hmmmm no text is in $error so do something else, the page has verified and the email was valid
  // so uncomment the line below to send the user to your own success page or wherever (swap yourpage.php with your files location).
  //echo "script type=\"text/javascript\">window.location=\yourpage.php\"<script>";  
  }
    else{
       echo "<span style=color:red>$error</span>";
    }                
}
?>

How come this doesn't work for my form??

Link to comment
Share on other sites

ok say you have a username, password and email address for your form and you want to check to see if its left empty before going to the DB

 

just use this: (if your method is POST in the form)

 


if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email'])) {

       // send info to the DB

}
else {

    echo "The Username, Password and/or email fields where left blank. Please fill out the form correctly.";

    // redirect back to the form

}

 

I hope this helps.

Link to comment
Share on other sites

Here's a similar method:

<?php
  $username=$_POST['username'];
  $password=$_POST['password'];
  $email=$_POST['email'];
  if (!empty($username)) {
    if (!empty($password)) {
      if (!empty($email)) {
        //send info to the db
      } else {echo "The email field mustn't be empty";}
    } else {echo "The password field mustn't be empty";}
  } else {echo "The username field mustn't be empty";}
?>

Admittedly it's a bit longer but this way you can tell the user which item is empty. You're also getting the contents of all 3 at the start so if you're setting the values back into a form you can do so with ease.

Link to comment
Share on other sites

So you think that I should put the verification code in the process repport

instead of the form.

Here is process_report.php with the changes, can I have some extra help

making sure that it works.

Thanks!

<?
$dbconn = @mysql_connect("localhost","username","password");
@mysql_select_db("database");

if (!empty($kb)) $kb = 1;
else $kb = 0;
        
       
if (isset($_POST['city']) && isset($_POST['state']) && isset($_POST['description']) && isset($_POST['summary'])) {

$strsql = "INSERT INTO database (`date`,`time`,`kb`,`city`,`state`,`zip`,`country`,`county`,`activity`,`description`,`summary`,`date`) 
VALUES ('$date','$time','$kb','$city','$state','$zip','$country','$county','$activity','$description','$summary',CURDATE());";
}
else{
   echo "The City, State, Description and/or Summary fields where left blank. Please fill out the form correctly.";
  [b]//How to send the user back to form.php [/b]
}

@mysql_query($strsql);

@mysql_close($dbconn);
?>	
<script type="text/javascript">
location.replace('form.php?m=1');
</script>

Is that right? If not please help. & also how do I send the user to the page

without asking them to fill everything again?

Link to comment
Share on other sites

If you use my method, the first three lines are getting the contents of the form and storing them in separate variables.

 

You can then "echo" them back into the form like this:

<input type="text" name="username" value="<?=$username?>" />

 

Do that with all of the lines of HTML in the form and you can give the user all the data they typed in.

Link to comment
Share on other sites

It seems a lot of work to echo all the fields

into the form, I have a long form.

what would the link back to the form be??

would it be a simple link to the form.php

or anything else.

Was there anything wrong with the process report

that I changed?

 

Link to comment
Share on other sites

Or using Archadian's method try this:

<input type="text" name="username" value="<?=$_POST['username']?>" />

AFAIK echo'ing the data back is really the only secure way to do it as it means the user doesn't have to hit their "back" button (risking losing/corrupting the data in $_POST) or having some javascript to do the same thing that can risk the same.

Link to comment
Share on other sites

So I should echo the whole form back to them

so they can make changes??

Can I save the form anyway even with the mistakes

and then echo the form so they can fix it?

It's like updating the form. I have an editpage.php page

that I used to edit entries, I can just change the name

to form2.php and ask them to make corrections...

What do you think???

Link to comment
Share on other sites

Whenever I make forms that gather data from the user I have similar PHP code at the start to get the data from the form. I then check if the submit button is pressed. If it is validate the data and do something with it. If it doesn't validate then tell the user why and carry on.

 

If the submit button wasn't pressed (or if the script is continuing) I then hit the HTML section of my script which builds the form. In each input tag I use value="" and use echo to echo the data back in if the submit button was pressed.

 

The first time the script is called the variables will be empty.

Link to comment
Share on other sites

Do you have an example of one of you form

it doesn't even have to contain the fields.

If you read the whole post, you can see that's

what I wanted to do but this is not what's

happenning.

I want to check the form before it gets process

to check the form for empy fields and tells the user

to fix them before the form gets process.

Thanks in advance!

Link to comment
Share on other sites

on your form the 'name="username"' you just insert the name of the "input" inside the ' ' in $_POST[' '] and check to see it something has been set to it with isset(). After all that is what you wanted right?

 

<input type="text" name="username"> = $_POST['username']

 

not hard :P

Link to comment
Share on other sites

Its got a bit more than you need. It's a "contact me" form to allow users to fill in information to email me.

<?php
  include("dbconnect.php");
  $opmode="gather";
  $prompt='<font color="#ffffff">Please complete the following form:</font>';
  if ($_POST['subsend']) {
    if ($_POST['usrname']) {
      $usrname=securestr($_POST['usrname']);
      if ($_POST['usremail']) {
        $usremail=securestr($_POST['usremail']);
        if ($_POST['usrsubject']) {
          $usrsubject=securestr($_POST['usrsubject']);
          if ($_POST['usrmessage']) {
            $usrmessage=securestr($_POST['usrmessage']);
            $header="From: ".$usrname." <".$usremail.">\r\n";
            $wherefrom=securestr($_POST['wherefrom']);
            if ($_POST['usrlink']) {$usrlink=securestr($_POST['usrlink']);} else {$usrlink="N/A";}
            if ($_POST['usrreply']) {$usrmessage.="\n\nUser would like a response.";}
            $usrip=GetHostByName($REMOTE_ADDR);
            $usrmessage.="\nRefer: $wherefrom ($usrlink)\nFrom IP $usrip";
            if (mail("MYEMAILREMOVED",$usrsubject,$usrmessage,$header)) {$opmode="sent";} else {$prompt='<font class="errmsg">Unable to send the email - please try again later</font>';}
          } else {$prompt='<font class="errmsg">You need to enter a message to send</font>';}
        } else {$prompt='<font class="errmsg">You need to supply a subject title</font>';}
      } else {$prompt='<font class="errmsg">You need to supply your email address</font>';}
    } else {$prompt='<font class="errmsg">You need to supply your name</font>';}
  }
  mysql_close($dbh);
  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<!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/10/xhtml" xml:lang="en" lang="en">
<head>
  <title>Picture In The Sky</title>
  <link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
  <center>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <table width="720" cellspacing="0" cellpadding="0" border="0">
<?php include("menu.php"); ?>
    <tr><td valign="bottom" class="title"><i>Contact Me</i></td></tr>
    <tr><td colspan="2"><hr /></td></tr>
    <tr>
      <td colspan="2" align="center">
<?php if ($opmode=="gather") { ?>
        <table width="100%" cellspacing="6" cellpadding="0" border="0" class="cmtext">
          <tr>
            <td align="center" width="100%">
              <?=$prompt?><br /><br />
              <table width="90%" cellspacing="0" cellpadding="2" class="sbox">
                <tr>
                  <td align="center">
                    <table width="96%" cellspacing="0" cellpadding="2" border="0">
                      <tr><td class="btext">Your Name</td><td><input type="text" name="usrname" size="30" maxlength="30" value="<?=$usrname?>" class="textbox" /></td></tr>
                      <tr><td class="btext">Your Email</td><td><input type="text" name="usremail" size="60" maxlength="60" value="<?=$usremail?>" class="textbox" /></td></tr>
                      <tr><td class="btext">Subject</td><td><input type="text" name="usrsubject" size="80" maxlength="30" value="<?=$usrsubject?>" class="textbox" /></td></tr>
                      <tr><td class="btext">Message</td><td><textarea name="usrmessage" rows="10" cols="84" class="textbox"><?=$usrmessage?></textarea></td></tr>
                      <tr><td class="btext">Reply?</td><td class="btext"><input type="checkbox" name="usrreply" /> (Tick if you would like a response)</td></tr>
                      <tr><td class="btext" colspan="2">How did you hear about my site? <select name="wherefrom" class="button"><option value="Link">Link from another site*</option><option value="Search Engine">Search Engine</option><option value="Friend">A friend</option><option value="Other">Other*</option></td></tr>
                      <tr><td class="btext">*site/other</td><td><input type="text" name="usrlink" size="80" maxlength="80" value="<?=$usrlink?>" class="textbox" /></td></tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr><td colspan="2" align="center">NOTE: No information will be supplied to third parties for advertising at any time<br /><br /><input type="submit" name="subsend" value="Send Email" class="button" /></td></tr>
        </table>
<?php } else { ?>
        <font size="2">Thank-you, your email has been sent!
<?php if ($_POST['usrreply']) {echo '<br /><br />I do read all of the emails I receive and will do my best to get back to you as soon as I can.</font>';} else {echo '</font>';} ?>
<?php } ?>
      </td>
    </tr>
    <tr><td colspan="2"><hr /></td></tr>
  </table>
  </form>
  </center>
</body>
</html>

Link to comment
Share on other sites

Thanks Yesideez for the example, I will try to use

some of these examples in your form.

 

I think maybe I should put my form here but it is for

a client and I don't want to mess up.

form.php

process_form.php

my form starts like this:

<form action="process_form.php" method="post" name="form" onsubmit="I have something here">

& I want something like this

	<tr>
	<td align="right" width="25%"><strong>City: </strong></td>
	<td align="left" width="75%">
        <input style="width:200px; " type="text" name="city" size="20"> 
        // I want to put something here that will check to see if it is empty and 
       tell the user that can't be empty before calling on process_form.php
</td>
</tr>

Link to comment
Share on other sites

The "contact me" script I posted is quite old now and you'll notice that after I check if the submit button was pressed I'm checking each form item if it contains anything. If it does, get the contents.  Just change the script so all data is obtained at the start then modify a couple of the if statements accordingly.

 

I use a variables called $opmode to determine what the user has achieved and what section of the HTML I want shown as everything is self-contained and there's no need to have a separate script saying thanks for sending me an email.

 

Have to go to bed now, just gone 11:30pm.

 

Hope you get it sorted!

Link to comment
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.