PHP - Form Values Dissapear In Captcha Validation
Hi everyone,
I am unable to get the any of the form values to stay after submission with captcha.
My code is below.
Please help. Also the error of the validation doesnt display on submission
<!DOCTYPE HTML> <html> <head> <style> .error {color: #FF0000;} .success {color:#360; background-color:#FF0;} .fail {color:#F00; background-color:#FFF;) </style> </head> <body> <?php if (isset($_POST['submit'])){ $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $country = $_POST['country']; $comment = $_POST['comment']; $gender = $_POST['gender']; $to = "laxmon@wikigets.com"; $subject = "New contact form submission"; $message =" A visitor of WIKIGETS has submited a form onine\n\n $name\n\n $email\n\n $phone \n\n $country \n\n $gender\n\n $comment"; require_once('recaptchalib.php'); $privatekey = "6LdK8_YSAAAAAJYPJduOpxhsL4Cy86NgwpCSJCod"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { header ("Location:contact.php?s=2"); } else { mail($to,$subject,$message); header ("Location:contact.php?s=1"); } } ?> <? $country_options= array("select","Afghanistan", "Ã…Land Islands", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua And Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia And Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, The Democratic Republic Of The", "Cook Islands", "Costa Rica", "Cote D'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island And Mcdonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran, Islamic Republic Of", "Iraq", "Ireland", "Isle Of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People'S Republic Of", "Korea, Republic Of", "Kuwait", "Kyrgyzstan", "Lao People'S Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia, The Former Yugoslav Republic Of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States Of", "Moldova, Republic Of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territory, Occupied", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Kitts And Nevis", "Saint Lucia", "Saint Pierre And Miquelon", "Saint Vincent And The Grenadines", "Samoa", "San Marino", "Sao Tome And Principe", "Saudi Arabia", "Senegal", "Serbia And Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia And The South Sandwich Islands", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard And Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province Of China", "Tajikistan", "Tanzania, United Republic Of", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad And Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks And Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam", "Virgin Islands, British", "Virgin Islands, U.S.", "Wallis And Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" ); // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = $countryErr = $phoneErr =""; $name = $email = $gender = $comment = $website = $phone = ""; $country =""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address syntax is valid if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["phone"])) { $phone = ""; } else { $phone = test_input($_POST["phone"]); $phone = preg_replace('/\D/', '', $phone); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } $country2 = $_POST['country']; $country3= "select"; if($country2!= $country3) { $country=$country2; } else { $country1 = "Please select your country";} } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>CONTACT US</h2> <p><?php $s=$_GET['s']; if($s=='1'){ Echo('<span class= "success"> Success!! An email has been sent to our web team. Please allow 24 hours for a response.</span>'); } else if ($s=='2') { Echo('<span class= "fail">Sorry! Please ensure to fill all feilds correctly</span>' ); } ?> </p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <p>Name: <input type="text" name="name" value="<?php echo $name;?>"> <span class="error">* <?php echo $nameErr1;?></span> <br><br> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php echo $emailErr1;?></span> </p> <p>Phone Number:<input type="text" name="phone" value="<?php echo $phone;?>"> <span class="error"> <?php echo $phoneErr1;?></span> <br> <br> Country: <?php $item = 'select'; echo '<select name="country">'; foreach($country_options as $c) { $sel=''; // Set $sel to empty initially $tag = 'selected="selected"'; if(isset($_POST['country']) && $_POST['country'] == $c) // Here we check if the form has been posted so an error isn't thrown and then check it's value against $c { $sel = $tag; } elseif(!isset($_POST['country']) && $item == $c) // So that the $item doesn't override the posted value we need to check to make sure the form has NOT been submitted also in the { $sel = $tag; } echo '<option value="'.$c.'" '.$sel.'>'.$c.'</option>'; } echo '</select>'; ?> <span class="error">*<?php echo (isset($country1)) ? $country1 : '';?></span> <br><br> <!--Website: <input type="text" name="website" value="<?php echo $website;?>"> <span class="error"><?php echo $websiteErr1;?></span> <br><br>--> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male <span class="error">* <?php echo $genderErr1;?></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> <br> <?php require_once('recaptchalib.php'); $publickey = "6LdK8_YSAAAAACMvxVRzJ7ZNqjQ9nT_dU6fEZdHx"; // you got this from the signup page echo recaptcha_get_html($publickey); ?> <br> <input type="submit" name="submit" value="Submit"> </p> </form> </body> </html> Edited by laxi, 16 July 2014 - 12:45 PM. Similar TutorialsHello, I have created a sing up form with email, password and captcha. I verify at submit all the possible errors and it works except one, for example you fill the email field with non existing email in db, the 2 password field with same pass and fill the captcha field wrong. In this example it will proceed inserting the data in the db, i cannot figure what is wrong please advise. register.php <?php session_start(); include('include/config.php'); include('include/validation.php'); include('include/header.php'); ?> <div id="register"> <h1>Inregistrare</h1> <?php if(isset($_POST['send']) && (!validateEmail($_POST['email']) || !validatePasswords($_POST['pass1'], $_POST['pass2']) || !validateRegister())): ?> <div id="error"> <ul> <?php if(!validateEmail($_POST['email'])): ?> <li><strong>E-mail invalid:</strong> Introduceti o adresa de email valida.</li> <?php endif ?> <?php if(!validatePasswords($_POST['pass1'], $_POST['pass2'])): ?> <li><strong>Parole invalide:</strong> Parolele nu se potrivesc sau sunt mai mici de 5 caractere!</li> <?php endif ?> <?php if(!validateCaptcha($_POST['code'])): ?> <li><strong>Cod invalid:</strong> Cod invalid.</li> <?php endif ?> <?php if(!validateRegister()): ?> <li><strong>Exista:</strong> exista.</li> <?php endif ?> </ul> </div> <form method="post" id="register" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>"> <div> <label for="email">E-mail</label> <input id="email" name="email" type="text" /> <span id="emailInfo">Adresa Dvs. de email va fi folosita pentru login.</span> </div> <div> <label for="pass1">Parola</label> <input id="pass1" name="pass1" type="password" /> <span id="pass1Info">Parola trebuie sa contina cel putin 5 caractere.</span> </div> <div> <label for="pass2">Confirma Parola</label> <input id="pass2" name="pass2" type="password" /> <span id="pass2Info">Confirma parola</span> </div> <div><img src="include/captcha.php" /></div> <div> <label for="code">Introduceti codul de mai sus</label> <input id="code" type="text" name="code" /> <span id="codeInfo">Sunteti om?</span> </div> <div> <input id="send" name="send" type="submit" value="Inregistrare" /> </div> </form> <?php elseif(isset($_POST['send'])):?> <div id="error" class="valid"> <ul> <li><strong>Felicitari!</strong> Datele de login au fost trimise la adresa <?php echo $_POST['email']; ?></li> </ul> </div> <?php $email=trim($_POST['email']); $password=md5($_POST['pass1']); $query="INSERT INTO users (email, password) VALUES ('$email', '$password')"; $result_query=mysql_query($query) or die('EROARE MYSQL'); ?> <?php endif ?> <?php if(!isset($_POST['send'])):?> <form method="post" id="register" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>"> <div> <label for="email">E-mail</label> <input id="email" name="email" type="text" /> <span id="emailInfo">Adresa Dvs. de email va fi folosita pentru login.</span> </div> <div> <label for="pass1">Parola</label> <input id="pass1" name="pass1" type="password" /> <span id="pass1Info">Parola trebuie sa contina cel putin 5 caractere.</span> </div> <div> <label for="pass2">Confirma Parola</label> <input id="pass2" name="pass2" type="password" /> <span id="pass2Info">Confirma parola</span> </div> <div><img src="include/captcha.php" /></div> <div> <label for="code">Introduceti codul de mai sus</label> <input id="code" type="text" name="code" /> <span id="codeInfo">Sunteti om?</span> </div> <div> <input id="send" name="send" type="submit" value="Inregistrare" /> </div> </form> <?php endif ?> </div> <?php include('include/footer.php'); ?> validation.php <?php function validateName($name){ //if it's NOT valid if(strlen($name) < 4) return false; //if it's valid else return true; } function validateEmail($email){ return ereg("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$", $email); } function validatePasswords($pass1, $pass2) { //if DOESN'T MATCH if(strpos($pass1, ' ') !== false) return false; //if are valid return $pass1 == $pass2 && strlen($pass1) > 4; } function validateMessage($message){ //if it's NOT valid if(strlen($message) < 10) return false; //if it's valid else return true; } function validateCaptcha($code) { if($code == $_SESSION['rand_code']) //if it's valid return true; else //if it's NOT valid return false; } function validateRegister() { $query_check_login="SELECT email FROM users WHERE email='".$_POST['email']."' LIMIT 1"; $result_check_login=mysql_query($query_check_login) or die('MYSQL ERROR'); $row_check = mysql_num_rows($result_check_login); if($row_check == 1){ //if it's NOT valid return false; } else { //if it's valid return true; } } ?> I'm using the following script: http://jsfiddle.net/VzVy6/8/ It give a alert message that slide in/out when a required field is still empty on submit. The script works fine, and in this example its only one field. When the field is empty I see the fade in alert message, and when the field has been filled in I see a normal popup alert message: alert("Would be submitting form"); I can't get it to work to change this alert message to a page POST submit. I was looking online, and I see Ajax examples that I don't get to work. What I want is that when all fields are filled in, that the form POST submit to another page including the values in the textboxes ofcourse. Maybe its something really easy, but I have already a headache because tried to get it to work for more then 5 hours in a row. Thank you for your time. I'm just learning about PHP and I'm diving in head first by attempting to modify our web site's contact form. I'm wishing to stop the form from erasing previously entered values upon "failed" data validation. It's of course going to be annoying to our visitors if their hardworked entries disappear just because they left out a name or entered an illegal email address. I regret that some potential solutions found on this forum and other locations on Google didn't seem to help on my page. As you can see, the validation is done with PHP's version of if-elseif-else. Later I'll be adding a reCAPTCHA and I hope that whatever I learn here might be useful for the potentially same problem when I am adding the CAPTCHA. The actual contact form is at http://www.woofwoofwoof.org/contact/index.php. Thank you in advance for your taking the time to help me what originally appeared to be a simple problem. I have read the rules and I hope I've followed the rules -- please let me know if I committed any sins of omission or commission. Now, for your Sunday reading pleasure, here's the code: CODE STARTS HERE ==================================== <?php include("../common/docType.php"); ?> <?php include("../common/htmlOpen.php"); ?> <head> <title><?php include("../common/titleBar.php"); ?> - Contact us!</title> <meta name="description" content="Call or email us with questions or orders."> <meta name="keywords" content="Barking Dog Chocolatiers, Charlotte NC, chocolate, contact us, telephone, email, e-mail"> <meta name="geo.placename" content="Charlotte, North Carolina"> <meta name="geo.region" content="US-NC"> <meta name="author" content="Joal Fischer"> <meta name="verify-v1" content="1aqZs7xrrfI3lp1RaWDkHHjY9UQZIbq2z/mIVdFeXiI=" /> <?php include("../common/headInclude.php"); ?> <script src="../common/common.js" type="text/javascript"></script> <link rel="Stylesheet" href="../css/contact.css" /> </head> <?php // Success/Fail message $msg = ""; $brisket = ""; // Target Email $targetEmail = "barkingdog@bellsouth.net"; // Process Submissions if(isset($_POST['submitted'])) { if($_POST['submitted']) { // process form. $guestName = $_POST['guestName']; $cityState = $_POST['cityState']; $emailAddress = $_POST['emailAddress']; $phone = $_POST['phone']; $msgSubject = "Barking Dog Chocolatiers Inquiry"; $msgContent = "FROM: $guestName\n"; $msgContent .= "City/State: $cityState\n"; $msgContent .= "Phone & time to call: $phone\n"; $msgContent .= "\nInquiry:\n"; $msgContent .= stripslashes($_POST['msgContent']); // Trial if then else reversed from Dan's original allowing maybe multiple tests in sequence -- in action if($guestName == "") { $keepvar = "1"; $msg = "<p style='color: red; font-weight: bold; font-size: 14px; margin: 12px 0px 0px 0px;'>Please enter a name!</p>"; } elseif($emailAddress == "") { $msg = "<p style='color: red; font-weight: bold; font-size: 14px; margin: 12px 0px 0px 0px;'>Please enter a valid email address!</p>"; } else { mail($targetEmail, $msgSubject, $msgContent, "From: $guestName <$emailAddress>\nX-Mailer:PHP/" . phpversion()); $msg = "<p style='color: darkgreen; font-weight: bold; font-size: 14px; margin: 12px 0px 0px 0px;'>Thank you! Your message has been sent.</p>"; $brisket = "<img src='../images/Brisket180x180web.jpg' width='180px' height='180px' alt='Brisket Says Hi' />"; } // Original if then else all commented out // if($emailAddress != "") { // mail($targetEmail, $msgSubject, $msgContent, "From: $guestName <$emailAddress>\nX-Mailer:PHP/" . phpversion()); // $msg = "<p style='color: darkgreen; font-weight: bold; font-size: 14px; margin: 12px 0px 0px 0px;'>Thank you! Your message has been sent.</p>"; // $brisket = "<img src='../images/Brisket180x180web.jpg' width='180px' height='180px' alt='Brisket Says Hi' />"; // } else { // $msg = "<p style='color: red; font-weight: bold; font-size: 14px; margin: 12px 0px 0px 0px;'>Please enter a valid email address!</p>"; // } } } ?> <body onload="loadMe('contact')"> <div id="container"> <div id="header"> <a href="../home/index.php" style="border:none"><div id="logo"></div></a> <div id="navBG"><?php include("../common/mainNav.php"); ?></div> </div><!--End Header--> <div id="contentArea"> <br /><img class="sideBox" src="../images/sideBox.jpg" width="12px" height="12px"><p class="sideItemSelected">contact us</p><br style="clear:both" /> <p class="sideItem"><a class="sideLink" href="./shipping.php">useful q & a</a></p> <div id="mainContent"> <h1>contact us</h1><br /> <h2>Have questions? Ready to order?<br /> <span style="color:#b5a072">Call 704.333.1595 Mon-Fri 9am - 5pm EST</span></h2> <p id="contactText" class="text">It's not business, it's personal! For instant answers to many questions about ordering, shipping, and other good stuff, please check the <a href="shipping.php">useful q&a</a> page. Nonetheless, we'll always be happy to answer your questions by phone or through the form below. We look forward to hearing from you.</p><br /> <div id="contactFormContainer"> <form method="post" id="contactForm" action="<?php echo($_SERVER['PHP_SELF']); ?>" > <div id="formContainer"> <input type="hidden" name="submitted" value="true" /> <input type="hidden" name="formname" value="contact" /> <div class="formRow"> <div class="itemSet"> <p class="itemLabel">Name</p> <input tabindex="1" class="itemContent" type="text" name="guestName" value='<?php echo $_POST[Name]; ?>' /> </div> <div class="itemSet"> <p class="itemLabel">City & state</p> <input tabindex="2" class="itemContent" type="text" name="cityState" /> </div> <br class="clearMe" /> </div> <div class="formRow"> <div class="itemSet"> <p class="itemLabel">Email Address</p> <input tabindex="3" class="itemContent" type="text" name="emailAddress" /> </div> <div class="itemSet"> <p class="itemLabel">Phone & best local time to call</p> <input tabindex="4" class="itemContent" type="text" name="phone" /> </div> </div> <div class="formRow"> <div> <p class="itemLabel">Your question</p> <textarea tabindex="5" id="msgContent" type="text" name="msgContent">Please telephone us to submit an order</textarea> </div> </div> <div class="formRow"> <div style="position: relative;"> <div style="float: left; margin-right: 40px;"> <input tabindex="6" id="submitButton" type="submit" name="submit" value="Submit" /> </div> <div style="float: left; margin-top: -10px;"> <?php //echo($msg); ?> </div> <br style="clear: both;" /> <div style="clear: both; position: absolute; top: -350px; left: -217px; width: 180px;"> <?php echo($msg); echo($brisket); ?> </div> <br style="clear: both;" /> </div> </div> </div> <!-- End Form Container --> </form> </div> <!-- End Contact Form --> </div> </div><!-- End Content Area--> <div id="bottomBar"></div> <?php include("../common/footer.php"); ?> </div><!-- End Container --> </body> </html> CODE STOPS HERE===================================== Hi, I really need to add a captcha to this PHP process form? How do I go about doing this? Code: [Select] <?php // Define some constants define( "RECIPIENT_NAME", "John Smith" ); define( "RECIPIENT_EMAIL", "john@example.com" ); define( "EMAIL_SUBJECT", "Visitor Message" ); // Read the form values $success = false; $senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : ""; $senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : ""; $message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : ""; // If all values exist, send the email if ( $senderName && $senderEmail && $message ) { $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">"; $headers = "From: " . $senderName . " <" . $senderEmail . ">"; $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers ); } // Return an appropriate response to the browser if ( isset($_GET["ajax"]) ) { echo $success ? "success" : "error"; } else { ?> <html> <head> <title>Thanks!</title> </head> <body> <?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?> <?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?> <p>Click your browser's Back button to return to the page.</p> </body> </html> <?php } ?> ?? Thanks in advance! Hello, I am trying to make a captcha, but having some trouble My code matches the tutorial I'm following, the 1st screenshot is the captcha.php file, the 2nd is the captcha_generate.php file, and the 3rd is the result in My browser, I am using firefox and linuxmint 10, with apache2 php5 and GD installed, any Help will be greatly appreciated!!!!! thanx GOD BLESS!!! [attachment deleted by admin] hi i was wondering if anyone had any idea how i can add code A to code b below? code a is my captcha code and code b is my contact form code thanks.. CODE A CAPTCHA: Code: [Select] <?php if(isset($_POST["captcha"])) if($_SESSION["captcha"]==$_POST["captcha"]) { echo 'CAPTHCA is valid; proceed the message'; } else { echo 'CAPTHCA is not valid; ignore submission'; } ?> CODE B CONTACT FORM: Code: [Select] <? $mailto = "me@blah.com"; $cc = ""; $bcc = ""; $subject = "Email subject"; $vname = "blah blah"; $email = $_POST['email']; function validateEmail($email) { if(eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$', $email)) return true; else return false; } if(strlen($_POST['name']) < 1 || strlen($_POST['message']) < 1 || validateEmail($email) == FALSE) { $emailerror = 'Error:'; if(empty($_POST['name'])) { $emailerror .= '<li>Enter name</li>'; } if(validateEmail($email) == FALSE) { $emailerror .= '<li>Enter valid email</li>'; } if(empty($_POST['message'])) { $emailerror .= '<li>Enter message</li>'; } } else { $emailerror .= "Your email has been sent successfully"; $timestamp = date("F j, Y, g:ia"); $messageproper ="\n\n" . "Name: " . ucwords($_POST['name']) . "\n" . "Email: " . ucwords($email) . "\n" . "Comments: " . $_POST['message'] . "\n" . "\n\n" ; $messageproper = trim(stripslashes($messageproper)); mail($mailto, $subject, $messageproper, "From: \"$vname\" <".$_POST['e_mail'].">\nReply-To: \"".ucwords($_POST['first_name'])."\" <".$_POST['e_mail'].">\nX-Mailer: PHP/" . phpversion() ); } ?> Just a bit of background first: I have a contact form set up on one of my domains. It hasn't been updated in 7 years and recently I started getting about 3-8 spam messages daily through it. At some point I updated other sites with code that includes a CAPTCHA.
Out of sheer laziness, instead of recoding the contact form that was getting spammed, I just copied & pasted one of the updated forms and changed the necessary details like which e-mail address, URL, etc. Unfortunately, this hasn’t worked out properly.
For some reason the CAPTCHA image isn’t being displayed. I keep looking but can't find the error(s). Could someone please take a look at the code and tell me what went wrong? I’d be ever so grateful for any help! The code for the form itself: <form method="post" action="mail-e.php"> <p><input type="text" name="name" id="name" value="who are you?" size="25" /></p> <p><input type="text" name="email" id="email" value="you@whatever.bla" size="25" /></p> <p><input type="text" name="url" id="url" value="http://" size="25" /></p> <p><textarea name="comments" id="comments" rows="1" cols="20">Go on, then. Tell me a story, wingy!</textarea></p> <p><img src="http://echoing.org/captcha.php" alt="humanity check" /><br /> <input type="text" name="captcha" id="captcha" /> <br /> <p><input type="submit" name="submit" id="submit" value="sing to me" /> <input type="reset" name="reset" id="reset" value="out of key" /></p> </form>mail-e.php: <?php session_start(); //Encrypt the posted code field and then compare with the stored key if(md5($_POST['captcha']) != $_SESSION['key']) { die("Error: You must enter the code correctly"); }else{ echo 'You entered the code correctly'; } ?> <?php if (!isset($_POST['submit'])) { include('./header.php'); echo "<h1>HEY!!! You just encountered an error!</h1>\n <p>You don't belong here. <strong>Because it's <em>wrong</em>.</strong> Go back and try again, please.</p>"; include('./footer.php'); exit; } function cleanUp($data) { $data = strip_tags($data); $data = trim(htmlentities($data)); return $data; } $name = cleanUp($_POST['name']); $email = cleanUp($_POST['email']); $url = cleanUp($_POST['url']); $comments = cleanUp($_POST['comments']); if ((empty($name)) || (empty($email)) || (empty($comments))) { include('./header.php'); echo "<h2>Input Error! Looks like you missed some stuff.</h2>\n <p><strong>Name</strong>, <strong>e-mail</strong> and <strong>comments</strong> are required fields. Please fill them in and try again:</p>"; echo "<form action=\"mail-e.php\" method=\"post\"><p>"; echo "<input type=\"text\" name=\"name\" id=\"name\" value=\"$name\" /> Name<br />"; echo "<input type=\"text\" name=\"email\" id=\"email\" value=\"$email\" /> E-mail<br />"; echo "<input type=\"text\" name=\"url\" id=\"url\" value=\"$url\" /> Site URL<br />"; echo "<textarea name=\"comments\" id=\"comments\">$comments</textarea> Comments<br />"; echo "<img src=\"http://echoing.org/captcha.php\" alt=\"humanity check\" style=\"margin-bottom: 2px;\" /><br />"; echo "<input type=\"text\" name=\"captcha\" id=\"captcha\" /> <br />"; echo "<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Send\" />"; echo "</p></form>"; include('./footer.php'); exit; } if (!ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$",$email)) { include('./header.php'); echo "<h2>Input Error</h2>\n <p>That e-mail address you entered - \"$email\" - is <em>not</em> a valid electronic address. Please edit it and send it in again, please:</p>"; echo "<form action=\"mail-e.php\" method=\"post\"><p>"; echo "<input type=\"text\" name=\"name\" id=\"name\" value=\"$name\" /> Name<br />"; echo "<input type=\"text\" name=\"email\" id=\"email\" value=\"$email\" /> E-mail<br />"; echo "<input type=\"text\" name=\"url\" id=\"url\" value=\"$url\" /> Site URL<br />"; echo "<textarea name=\"comments\" id=\"comments\">$comments</textarea> Comments<br />"; echo "<img src=\"captcha.php\" alt=\"humanity check\" style=\"margin-bottom: 2px;\" /><br />"; echo "<input type=\"text\" name=\"captcha\" id=\"captcha\" /> <br />"; echo "<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Send\" />"; echo "</p></form>"; include('./footer.php'); exit; } $email = preg_replace("([\r\n])", "", $email); $find = "/(content-type|bcc:|cc:)/i"; if (preg_match($find, $name) || preg_match($find, $email) || preg_match($find, $url) || preg_match($find, $comments)) { include('./header.php'); echo "<h1>Error</h1>\n <p>No meta/header injections, please.</p>"; include('./footer.php'); exit; } $recipient = "my email address is here"; $subject = "paint me a wish on a velvet sky"; $message = "Name: $name \n"; $message .= "E-mail: $email \n"; $message .= "URL: $url \n"; $message .= "Comments: $comments"; $headers = "From: a wish painted on the velvet sky \r\n"; $headers .= "Reply-To: $email"; if (mail($recipient,$subject,$message,$headers)) { include('./header.php'); echo "<<p>WOO HOO! Your message was successfully sent to me! I'll read it as soon as I can. I may even respond! Thanks for using the form, fruitcake :)</p>"; include('./footer.php'); } else { include('./header.php'); echo "<p>Something went awry. Your message didn't go through. Want to take another crack at it? Please do, I'd love to hear from you!</p>"; include('./footer.php'); } ?>captcha.php: <?php //Start the session so we can store what the code actually is. session_start(); //Now lets use md5 to generate a totally random string $md5 = md5(microtime() * mktime()); /* We dont need a 32 character long string so we trim it down to 5 */ $string = substr($md5,0,5); /* Now for the GD stuff, for ease of use lets create the image from a background image. */ $captcha = imagecreatefromjpeg("http://echoing.org/captcha.jpg"); /* Lets set the colours, the colour $line is used to generate lines. Using a blue misty colours. The colour codes are in RGB */ $black = imagecolorallocate($captcha, 0, 0, 0); $line = imagecolorallocate($captcha,233,239,239); /* Now to make it a little bit harder for any bots to break, assuming they can break it so far. Lets add some lines in (static lines) to attempt to make the bots life a little harder */ imageline($captcha,0,0,39,29,$line); imageline($captcha,40,0,64,29,$line); /* Now for the all important writing of the randomly generated string to the image. */ imagestring($captcha, 5, 20, 10, $string, $black); /* Encrypt and store the key inside of a session */ $_SESSION['key'] = md5($string); /* Output the image */ header("Content-type: image/jpeg"); imagejpeg($captcha); ?>I don’t know where it all went wrong as I’m using pretty much the same code without problems here, here and here. The form isn't being used presently (apart from the spam) but I am itching to know what the problem is. P.S. The link to the CAPTCHA image wasn’t always http://echoing.org/captcha.php in the code. On the other forms and initially with this one the code was ./captcha.php but I changed it in case that was the problem. Looks like it isn’t. Thanks in advance! HI recently we have been starting to recieved about 30 spam emails aday. I read that the issue was how my forms were submitting and that it kept bypassing the javascript. I found some code i could use at http://chrisplaneta....with_recaptcha/ but i cannot seem to get the form to function correctly.
It is supposed to email me once the form is validated but the email does not seem to be sending.
Also i would like the form to redirect to a thank you page once it has been agreed. I did try but it kept telling me the headers had already been called. i am calling the page in with php include. Can you please advise the best way for me to relocate.
I have attached a copy of my form.php page which has every thing on. I have also included the code at the bottom of this email
Also i would appreciate any comments on what i can include on my form to limit the spammers
<?php //If the form is submitted: if(isset($_POST['submitted'])) { //load recaptcha file require_once('captcha/recaptchalib.php'); //enter your recaptcha private key $privatekey = "6Ld5Df4SAAAAAKciqwDco8dfvBR15fGeFVXWcvCO"; //check recaptcha fields $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); //Check to see if the invisible field has been filled in if(trim($_POST['checking']) !== '') { $blindError = true; } else { //Check to make sure that a contact name has been entered $authorName = (filter_var($_POST['formAuthor'], FILTER_SANITIZE_STRING)); if ($authorName == ""){ $authorError = true; $hasError = true; }else{ $formAuthor = $authorName; }; //Check to make sure sure that a valid email address is submitted $authorEmail = (filter_var($_POST['formEmail'], FILTER_SANITIZE_EMAIL)); if (!(filter_var($authorEmail, FILTER_VALIDATE_EMAIL))){ $emailError = true; $hasError = true; } else{ $formEmail = $authorEmail; }; //Check to make sure the subject of the message has been entered $msgSubject = (filter_var($_POST['formSubject'], FILTER_SANITIZE_STRING)); if ($msgSubject == ""){ $subjectError = true; $hasError = true; }else{ $formSubject = $msgSubject; }; //Check to make sure content has been entered $msgContent = (filter_var($_POST['formContent'], FILTER_SANITIZE_STRING)); if ($msgContent == ""){ $commentError = true; $hasError = true; }else{ $formContent = $msgContent; }; // if all the fields have been entered correctly and there are no recaptcha errors build an email message if (($resp->is_valid) && (!isset($hasError))) { $emailTo = 'carlycyber@hotmail.co.uk'; // here you must enter the email address you want the email sent to $subject = 'A new message from: immigration solicitors Manchester' ; $body = "Name :formAuthor \n\nEmail: $formEmail \n\nTelephone :formSubject \n\nContent: $formContent \n\n$formAuthor"; // This is the body of the email $headers = 'From: <'.$formEmail.'>' . "\r\n" . 'Reply-To: ' . $formEmail . "\r\n" . 'Return-Path: ' . $formEmail; // Email headers // Email headers //send email mail($emailTo, $subject, $body, $headers); // set a variable that confirms that an email has been sent $emailSent = true; } // if there are errors in captcha fields set an error variable if (!($resp->is_valid)){ $captchaErrorMsg = true; } } } ?> <?php // if the page the variable "email sent" is set to true show confirmation instead of the form ?> <?php if(isset($emailSent) && $emailSent == true) { ?> <?php $message = "Thank you. Your form has been submitted and a member of our team will contact you shortly.This website is developed for generating immigration enquiries in your area and it is not a law firm, your enquiries will be passed on to a solicitor.We confirm that this website does not belong to a law firm and we have no physical office in your county. Our solicitors are able to provide immigration services all over the UK because they provide a Virtual Service.Responses to your legal enquiries and the legal opinion given to you would be provided by a qualified UK Immigration Solicitor. If you decide to proceed with the solicitor, your matter will be dealt with under a Law firm regulated by the Solicitors Regulatory Authority."; echo "<script type='text/javascript'>alert('$message');</script>"; /*echo "<script language='javascript'> window.location('http://www.immigrationsolicitorsmanchesteruk.co.uk/thankyou.php') </script>";*/ ?> <p>Thank you. Your form has been submitted and a member of our team will contact you shortly.This website is developed for generating immigration enquiries in your area and it is not a law firm, your enquiries will be passed on to a solicitor.We confirm that this website does not belong to a law firm and we have no physical office in your county. </p> <?php } else { ?> <?php // if there are errors in the form show a message ?> <?php if(isset($hasError) || isset($blindError)) { ?> <p><strong>Im sorry. There was an error submitting the form. Please check all the marked fields and try again.</strong></p> <?php } ?> <?php // if there are recaptcha errors show a message ?> <?php if ($captchaErrorMsg){ ?> <p><strong>The recaptcha was not entered correctly. Please try again.</strong></p> <?php } ?> <?php // here, you set what the recaptcha module should look like // possible options: red, white, blackglass and clean // more infor on customisation can be found he http://code.google.com/intl/pl-PL/apis/recaptcha/docs/customization.html ?> <script type="text/javascript"> var RecaptchaOptions = { theme : 'blackglass' }; </script> <?php // this is where the form starts // action attribute should contain url of the page with this form // more on that you can read he http://www.w3schools.com/TAGS/att_form_action.asp ?> <form id="contactForm" action="" method="post"> <p> <strong>Full Name</strong><br/> <input class="requiredField <?php if($authorError) { echo 'formError'; } ?>" type="text" name="formAuthor" id="formAuthor" value="<?php if(isset($_POST['formAuthor'])) echo $_POST['formAuthor'];?>"size="25" /></p> <p> <strong>Email </strong><br/> <input class="requiredField <?php if($emailError) { echo 'formError'; } ?>" type="text" name="formEmail" id="formEmail" value="<?php if(isset($_POST['formEmail'])) echo $_POST['formEmail'];?>" size="25" /> </p> <p> <strong>Telephone </strong><br/> <input class="requiredField <?php if($subjectError) { echo 'formError'; } ?>" type="text" name="formSubject" id="formSubject" value="<?php if(isset($_POST['formSubject'])) echo $_POST['formSubject'];?>" size="25" /> </p> <p> <strong>Please give us some information about your enquiry</strong><br/> <textarea class="requiredField <?php if($commentError) { echo 'formError'; } ?>" id="formContent" name="formContent" cols="25" rows="5"><?php if(isset($_POST['formContent'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['formContent']); } else { echo $_POST['formContent']; } } ?></textarea></p> <?php // this field is visible only to robots and screenreaders // if it is filled in it means that a human hasn't submitted this form thus it will be rejected ?> <div id="screenReader"> <label for="checking"> If you want to submit this form, do not enter anything in this field </label> <input type="text" name="checking" id="checking" value="<?php if(isset($_POST['checking'])) echo $_POST['checking'];?>" /> </div> </div> <?php // load recaptcha file require_once('captcha/recaptchalib.php'); // enter your public key $publickey = "6Ld5Df4SAAAAANFKozja9bUlDziJ92c31DDt1j6k"; // display recaptcha test fields echo recaptcha_get_html($publickey); ?> <input type="hidden" name="submitted" id="submitted" value="true" /> <?php // submit button ?> <input type="submit" value="Send Message" tabindex="5" id="submit" name="submit"> </form> <?php } // yay! that's all folks! ?>Attached Files form issue.txt 7.58KB 1 downloads I have a basic question for anyone that can help me. Ive added a captcha input field to the form below, as Im having problems with spam appearing on my testimonial page. 1) How can I prevent the form from being sent if the wrong or no answer is in the form field. 2) How can i have a message appear saying "Sorry wrong answer" if the from isnt sent for the above reason? add.php Code: [Select] <form method="post" action="process2.php" > <textarea rows="25" cols="100" wrap="physical" name="data"> </textarea> <input type="hidden" name="area" value="testimonial"/> What is 5+5? <input type="text" name="captcha"/> <input type="submit" value="Add "> </form> process2.php Code: [Select] <p class="add">Thankyou for submitting your testimonial;</br> <?php $data="<br><br>" . $_POST["data"]; ?><br /> <?php $area=$_POST["area"]; ?> <?php echo $data; ?></p> <?php mysql_query("UPDATE wheelchairwizard SET data = CONCAT(data, '$data') WHERE area = '$area'"); ?> </br> Return to the testimonial page - <a href="http://www.wheelchairwizard.co.uk/testimonials.php">click here</a> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=319400.0 Hi, im trying to have a math captcha in my registration form, but having trouble with setting it up in my form. sorry for the large code. If i change the value of $_POST['Submit'] to something else like $_POST['Submit1'] and then same for the math image captcha then it works, but i would like it to work as part of the form, makes sense? lol right now the form just posts the value and doesnt check for captcha values! if someone could help me out here that would be great! thank you. Code: [Select] <?php if(isset($_POST['Submit'])){ if($_POST['Submit'] != $_SESSION['security_number']) { $error = ""; } else { $error = ""; } //NEED TO CHECK IF FIELDS ARE FILLED IN if( empty($_POST['name']) && (empty($_POST['email']))){ header("Location:Messages.php?msg=3"); exit(); } if( empty($_POST['pw1']) && (empty($_POST['pw2']))){ header( "Location:Messages.php?msg=4" ); exit(); } $name=$_POST['name']; $email=$_POST['email']; $pw1=$_POST['pw1']; $pw2=$_POST['pw2']; if("$pw1" !== "$pw2" ){ header( "Location:Messages.php?msg=5" ); exit(); } $ip = $_SERVER['REMOTE_ADDR']; //connect to the db server , check if uname exist include('config.php'); $query1=("Select * from user where email='$email'"); $result1= mysql_query($query1); $num1=mysql_num_rows($result1); if ($num1 > 0) {//Email already been used header( "Location:Messages.php?msg=11" ); exit(); }else{ $query=("Select * from user where uname='$name'"); $result= mysql_query($query); $num=mysql_num_rows($result); if ($num > 0) {//Username already exist header( "Location:Messages.php?msg=6" ); exit(); }else{ //if username does not exist insert user details $query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level) VALUES ('$name',md5('$pw1'),'$email',NOW(),'$ip','Normal')"); if (@mysql_query ($query)) { header("location:login.php?reg=1"); exit; } } } mysql_close(); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><!-- InstanceBegin template="/Templates/Auth.dwt.php" codeOutsideHTMLIsLocked="false" --> <head> <!-- InstanceBeginEditable name="doctitle" --> <title>Registration</title> <!-- InstanceEndEditable --> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <!-- InstanceBeginEditable name="head" --> <!-- InstanceEndEditable --> <link href="styleLog.css" rel="stylesheet" type="text/css"> <script language="javascript" type="text/javascript"> function reloadCaptcha() { document.getElementById('captcha').src = document.getElementById('captcha').src+ '?' +new Date(); } </script> </head> <body> <table width="100%" border="0" cellspacing="7" cellpadding="0"> <tr class="temptitle"> <td><!-- InstanceBeginEditable name="EditRegion4" -->New User Registration <!-- InstanceEndEditable --></td> </tr> <tr> <td><!-- InstanceBeginEditable name="EditRegion3" --> <form name="form1" action="register.php" method="post"> <table width="657" border="0"> <tr> <td width="122"><div align="left">Name</div></td> <td width="525"><input name="name" type="text" size="40"></td> </tr> <tr> <td><div align="left">Email</div></td> <td><input name="email" type="text" size="40"></td> </tr> <tr> <td><div align="left">Password</div></td> <td><input name="pw1" type="password" size="40"></td> </tr> <tr> <td ><div align="left">Confirm Password </div></td> <td><input name="pw2" type="password" size="40"></td> </tr> <tr> <td><img src="math_captcha/image.php" alt="Click to reload image" title="Click to reload image" id="captcha" onclick="javascript:reloadCaptcha()" /></td> <td><input type="text" name="Submit" value="what's the result?" onclick="this.value=''" /></td> <td> </tr> <tr> <td></td> <td> <input name="Submit" type="submit" value="Register"></td> </tr> </table> </form> <?=$error?> MOD EDIT: code tags added. Hi guys, I am having a real problem with this and I can't figure it out. I am not that much of a techie so take it easy on me. I am building a survey form for a website to get feedback on the service, and naturally it can fail validation if the email address is misspelled or the security question is answered wrong. Retaining text values was easy and I managed to dig around for some solutions to retain radio button values. The problem is IT ONLY WORKS ON ONE OPTION! I tried everything including coming up with completely separate value names, yet the page still loads with all radio options set to the same shared value (usually of the last radio button question). Here is my code: <?PHP $Excellent_status = 'unchecked'; $VeryGood_status = 'unchecked'; $Satisfactory_status = 'unchecked'; $Weak_status = 'unchecked'; $Horrible_status = 'unchecked'; if (isset($_POST['send'])) { $selected_tk = $_POST['tk']; if ($selected_tk == 'Excellent') { $Excellent_status = 'checked'; } else if ($selected_tk == 'VeryGood') { $VeryGood_status = 'checked'; } else if ($selected_tk == 'Satisfactory') { $Satisfactory_status = 'checked'; } else if ($selected_tk == 'Weak') { $Weak_status = 'checked'; } else if ($selected_tk == 'Horrible') { $Horrible_status = 'checked'; } } $Excellent2_status = 'unchecked'; $VeryGood2_status = 'unchecked'; $Satisfactory2_status = 'unchecked'; $Weak2_status = 'unchecked'; $Horrible2_status = 'unchecked'; if (isset($_POST['send'])) { $selected_ts = $_POST['ts']; if ($selected_ts == 'Excellent') { $Excellent2_status = 'checked'; } else if ($selected_ts == 'VeryGood') { $VeryGood2_status = 'checked'; } else if ($selected_ts == 'Satisfactory') { $Satisfactory2_status = 'checked'; } else if ($selected_ts == 'Weak') { $Weak2_status = 'checked'; } else if ($selected_ts == 'Horrible') { $Horrible2_status = 'checked'; } } ?> <h1 align="center">Feedback Form:</h1> <p align="center">We highly value your input. Your feedback can help us serve you better and provide you with a holistic experience that meets or exceeds all your expectations. <br /> Please take the time to fill out the form below.</p> <br /> <br /> <p align="center"><strong>(Fields marked with a <span class="required">*</span> are necessary. The course information is to validate which course and batch the survey is regarding, and the name and email allows our admin to verify the details and gain more information from you if needed)</strong></p> <p align="center"><strong>The identity in this form is strictly confidential, and it will not be revealed to course trainer, co-ordinator, or your sponsor.</strong></p> <!--Error Message--> <?php echo $error;?> <form method="post" name="contFrm" id="contFrm" action=""> <label><span class="required">*</span>Name:</label> <input name="name" type="text" class="box" id="name" size="40" value="<?php echo $name;?>" /><br /> <label><span class="required">*</span>Email: </label> <input name="email" type="text" class="box" id="email" size="40" value="<?php echo $email;?>" /><br /> <label><span class="required">*</span>Course attended: </label> <input name="course" type="text" class="box" id="course" size="40" value="<?php echo $course;?>" /><br /> <label><span class="required">*</span>Course Date and City: </label> <input name="dateplace" type="text" class="box" id="dateplace" size="40" value="<?php echo $dateplace;?>" /><br /><br /><br /> <table width="980" border="1" cellpadding="5" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td width="280" align="left" bgcolor="#285A80"><strong><font color="#FFFFFF" size="+1">Attribute</font></strong></td> <td width="115"> <div align="center">EXCELLENT! </div></td> <td width="115"> <div align="center">Really Good. </div></td> <td width="115"> <div align="center">Satisfactory. </div></td> <td width="115"> <div align="center">Weak, needs attention. </div></td> <td width="115"> <div align="center">Horrible! Unacceptable. </div></td> </tr> <tr> <td width="280" align="left" bgcolor="#71C4CD"><strong><font color="#333333">Trainer Knowledge</font></strong></td> <td> <div align="center"> <input type="radio" name="tk" id="Excellent" value="Excellent" <?PHP print $Excellent_status; ?>/> </div> </td> <td> <div align="center"> <input type="radio" name="tk" id="VeryGood" value="VeryGood" <?PHP print $VeryGood_status; ?>/> </div> </label></td> <td> <div align="center"> <input type="radio" name="tk" id="Satisfactory" value="Satisfactory" <?PHP print $Satisfactory_status; ?>/> </div> </td> <td> <div align="center"> <input type="radio" name="tk" id="Weak" value="Weak" <?PHP print $Weak_status; ?>/> </div> </td> <td> <div align="center"> <input type="radio" name="tk" id="Horrible" value="Horrible" <?PHP print $Horrible_status; ?>/> </div> </td> </tr> <tr> <td width="280" align="left" bgcolor="#71C4CD"><strong><font color="#333333">Trainer Style and Presentation</font></strong></td> <td> <div align="center"> <input type="radio" name="ts" id="Excellent2" value="Excellent2" <?PHP print $Excellent2_status; ?>/> </div> </td> <td> <div align="center"> <input type="radio" name="ts" id="VeryGood2" value="VeryGood2" <?PHP print $VeryGood2_status; ?>/> </div> </label></td> <td> <div align="center"> <input type="radio" name="ts" id="Satisfactory2" value="Satisfactory2" <?PHP print $Satisfactory2_status; ?>/> </div> </td> <td> <div align="center"> <input type="radio" name="ts" id="Weak2" value="Weak2" <?PHP print $Weak2_status; ?>/> </div> </td> <td> <div align="center"> <input type="radio" name="ts" id="Horrible2" value="Horrible2" <?PHP print $Horrible2_status; ?>/> </div> </td> </tr> </table> <br /><br /> <label>Particularly positive points you appreciated: </label> <textarea name="message1" cols="80" rows="3" id="message1"><?php echo $message1;?> </textarea><br /> <label>Particularly negative points you found disappointing: </label> <textarea name="message2" cols="80" rows="3" id="message2"><?php echo $message2;?> </textarea><br /> <label>Any specific message you would like to provide us: </label> <textarea name="message3" cols="80" rows="3" id="message3"><?php echo $message3;?> </textarea><br /> <label><span class="required">* Security Question</span></label><? require_once ("ClassMathGuard.php"); MathGuard::insertQuestion(); ?> <br /> <br /> <!-- Submit Button--> <input name="send" type="submit" class="button" id="send" value="" /> </form> Fact is there are 8 questions (all multiple choice with radio button answers) but I decided to save you a long code read. Basically what I get is that despite choosing different answers for each question, the retention is only of the last option or question, and all the above question choices are set to that choice button. What is wrong? Hi, I currently have the following code in my form processing script: Code: [Select] $string_exp = "/^[A-Za-z .'-]+$/"; $error_missing = 'This field is required'; if(!preg_match($string_exp,$Name)) { $errors[] = $error_missing; } if(!preg_match($string_exp_number,$Phone)) { $errors[] = $error_missing; } if(is_array($errors)) { echo 'Your message could not be sent due to the following errors:'; while (list($key,$value) = each($errors)) { echo '<span class="error">'.$value.'</span><br />'; } If the user enters no data into the required fields, the script prevents the form from being submitted and displays an error. At present the errors for all the required fields are displayed in a long list at the top of my HTML form e.g. This field is required This field is required What I want to do, is place the error message under each required field e.g. this http://coreyworrell.com/assets/uploads/images/ajax_contact_form.png instead of this http://cdn1.1stwebdesigner.com/wp-content/uploads/2010/02/validation-ajax-css-form.jpg What do I need to do? My form looks similar to this at the moment: Code: [Select] <div id="log"> <div id="log_res"> </div> </div> <form id="contact" name="contact" method="post" action="process.php"> <label>Name</label> <input type="text" name="Name" id="Name" tabindex="1" /> <label>Email</label> <input type="text" name="Phone" id="Phone" tabindex="2" /> </form> The error messages are placed in the <div> section at the top of the form (using ajax) Hi Guys, Im a bit of a novice to Php but somehow I've managed to get myself a form together for customers to book online. My problem is that i need to validate all the input's of my form. To give you some idea of what i mean. The $name should only contain letters and be no longer than 25 characters. The $address should only contain letters & numbers and be no longer than 40 characters. The $district and $town should only contain letters and be no longer than 30 characters each. The $postcode should only contain letters and Numbers and be no longer than 8 characters, it should start and end with a letter if thats possible. The $phone should only contain numbers and be no longer than 11 characters. And the email, well im lost with how that should be set out because of all the different options you can have. Anyway, this is my code: <?php $to = 'myemail.com' ; $from = $_REQUEST['Email'] ; $name = $_REQUEST['Name'] ; $phone = $_REQUEST['Phone']; $headers = "From: $from"; $subject = "Booking Request"; $fields = array(); $fields{"Name"} = "Name"; $fields{"Address"} = "Address"; $fields{"District"} = "District"; $fields{"Town"} = "Town"; $fields{"Postcode"} = "Postcode"; $fields{"Phone"} = "Phone"; $fields{"Email"} = "Email"; $fields{"list"} = "Mailing List"; $fields{"Message"} = "Message"; $body = "We have received the following information:\n\n"; foreach($fields as $a => $b) { $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } if ($name == '') {print "You have not entered a name, please go back and try again";} elseif ($phone == '') {print "You have not entered a Phone number, please go back and try again";} else { $send = mail($to, $subject, $body, $headers); if($send) {header( "Location: http://www.(not applicable).com" );} else {print "We encountered an error sending your mail, please notify webmaster@YourCompany.com"; } } ?> Any help is greatly apprecaited. Kind regards Rich I am asking for some simple help, please. :-) I have a form that I would like to validate very specific information on - without having it validate in the php and loose what the client just put into the site. I have found an example in this "validation" process. However, when I open this up in Dreamweaver CS4, I have an error on line 67 as a syntex error. I am unable to see where this would be. All I need is a verification on the name, the phone number, and the email address. Here is what I have so far.... **This is contact form** Code: [Select] <script language="JavaScript"> function checkForm() { var cname, cemail, cphone with(window.document.Contact1) { cname = name; cemail = EmailFrom; cphone = phone; } if(trim(cname.value) == '') { alert('Please enter your name'); cname.focus(); return false; } else if(trim(cemail.value) == '') { alert('Please enter your email'); cemail.focus(); return false; } else if(!isEmail(trim(cemail.value))) { alert('Email address is not valid'); cemail.focus(); return false; } else if(trim(cphone.value) == '') { alert('Please enter message subject'); csubject.focus(); return false; } } else { cname.value = trim(cname.value); cemail.value = trim(cemail.value); cphone.value = trim(cphone.value); return true; } } function trim(str) { return str.replace(/^\s+|\s+$/g,''); } function isEmail(str) { var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag| ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg| bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg| ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb| gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn| hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg| kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly| ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum| mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu| nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa| re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st| su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz| ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i; return regex.test(str); } </script> Below is the php file that I am using.... Code: [Select] <!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=iso-8859-1" /> <title>Emailing Form Data</title> </head> <body> <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); //declaration of variables $EmailFrom = trim(stripslashes($_POST['EmailFrom'])); $EmailTo = "ornclo@aol.com"; $Subject = "Women United Contact"; $Name = trim(stripslashes($_POST['name'])); $Address = trim(stripslashes($_POST['address'])); $City = trim(stripslashes($_POST['city'])); $State = trim(stripslashes($_POST['state'])); $Phone1 = trim(stripslashes($_POST['phone1'])); $Phone2 = trim(stripslashes($_POST['phone2'])); $Phone3 = trim(stripslashes($_POST['phone3'])); $email = trim(stripslashes($_POST['email'])); foreach ($_POST['visit'] as $value) { $Church = trim(stripslashes($value)); } foreach ($_POST['hear'] as $hear) { $About = trim(stripslashes($hear)); } foreach ($_POST['help'] as $help) { $Ask = trim(stripslashes($help)); } $Comments = trim(stripslashes($_POST['comments'])); // validation $validationOK=true; if (($EmailFrom)=="") $validationOK=false; if (($Name)=="") $validationOK=false; if (($Phone1)=="") $validationOK=false; if (($Phone2)=="") $validationOK=false; if (($Phone3)=="") $validationOK=false; if (($email)=="") $validationOK=false; if (($Comments)=="") $validationOK=false; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; exit; } // prepare email body text $Body = "\n"; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Address: "; $Body .= $Address; $Body .= "\n"; $Body .= "City: "; $Body .= $City; $Body .= "\n"; $Body .= "State: "; $Body .= $State; $Body .= "\n"; $Body .= "Phone: "; $Body .= $Phone1; $Body .= "-"; $Body .= $Phone2; $Body .= "-"; $Body .= $Phone3; $Body .= "\n"; $Body .= "Attended Church of God?: "; $Body .= $Church; $Body .= "\n"; $Body .= "How did you hear about us?: "; $Body .= $About; $Body .= "\n"; $Body .= "What can we do to help you?: "; $Body .= $Ask; $Body .= "\n"; $Body .= "Comments: "; $Body .= $Comments; $Body .= "\n"; // send email $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); // redirect to success page if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=WUok.html\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; } ?> </body> </html> Unless there is a way to change this line: print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; to have it keep in the same window - or even possibly open a NEW window with the "error.html" - that would be fine as well. Again - when I open up Contact1.html in DW CS4, I get a syntext error on line 67. When I use just straight form, it opens to new window with php - > error.html, which in turns looses everything the client just typed. Any help is greatly appreciated and thank you in advance. Blessings! If asked, I can attach the files if needed as well, but the code is pretty self-explain. I want in my form to validate on the fly(when the user enters the user name) to validate if the user name exists or not. How am i supposed to check if the field name is the same or not with a name in the database.Should i use ajax or javascript? is there any simple example on how to do that. Hi there, I've got a HTML textarea with the name attribute of 'review' and I've posted this into a variable called $review. I want to say if the characters are less than 30, please enter more words etc. The problem is, I get the if statement's error even when there are more than 30 characters. Can anyone figure out why I'm getting this? Code: [Select] if ($review < 30){ echo '<p class="red">Review is too short, please enter at least 15 words</p>'; } Hi all! Im trying to modify a script so that when a user submits data on a form if there are any errors it flags all errors and not just the first one the script comes to and 'dies'. Heres the form code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <html> <head> <title>Sample AJAX Web Form</title> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> function sendRequest() { new Ajax.Request("ajaxvalidate.php", { method: 'post', parameters: 'name='+$F('name')+'&phonenumber='+$F('phonenumber')+'&age='+$F('age')+'&captcha='+$F('captcha'), onComplete: showResponse }); } function showResponse(req){ $('show').innerHTML= req.responseText; } </script> <style type="text/css"> P.yellow {background-color: #ffff00;} </style> </head> <body> <h3>This is a sample PHP web form with AJAX validation</h3> Please complete the form below and then press "Submit button".<br /> <br /><br /> <form action="/ajaxwebform/ajaxvalidate.php" method="post" onsubmit="return false;"> Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br /> <input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50"> <br /><br /> Enter your Phone number (numbers only, no dashes and spaces)<br /> <input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35"> <br /><br /> Enter your Age (Numbers only)<br /> <input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50"> <br /><br /> <img src="/ajaxwebform/captcha.php" /> <br /> Enter the Captcha as shown above: <br /> <br /> <input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10"> <br /> <br /> <input type="submit" value="Submit" onClick="sendRequest()"> </form> <br /> This form will validate your data entry using AJAX. If you are correct with your data entry, the entire information entered will be shown in this page without reloading. <br /> <br /><br /> <p class="yellow" id="show"></p> </body> </html> Heres the php validating code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <?php //start session to recover captcha answers //connect to database $username = "root"; $password = ""; $hostname = "localhost"; $database = "newdb"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db($database,$dbhandle) or die("Could not select $database"); //extract form inputs $name =$_POST['name']; $phonenumber =$_POST['phonenumber']; $age =$_POST['age']; $usercaptchaanswer =$_POST['captcha']; $correctcaptcha = $_SESSION['answer']; //sanitize early for any possible MySQL entry $name = mysql_real_escape_string(stripslashes(trim($name))); $phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber))); $age = mysql_real_escape_string(stripslashes(trim($age))); $usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer))); $correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha))); Validate captcha entry if ($correctcaptcha != $usercaptchaanswer) { echo 'ERROR: You have entered wrong captcha code'; die (); } //Step 2 of data validation: check for blank entries if (empty($name)) { //name field is blank echo 'ERROR: The name field is empty.'; die (); } if (empty($phonenumber)) { //phone field is blank echo 'ERROR: The phone field is empty.'; die (); } if (empty($age)) { //age field is blank echo 'ERROR: The age field is empty.'; die (); } if (empty($usercaptchaanswer)) { captcha field is blank echo 'ERROR: The captcha field is empty.'; die (); } //Step 3 of data validation: Ensuring correct format //Step 3.1 validate full name, presence of first name and last name $mystring = $name; $findme = ' '; $pos = strpos($mystring, $findme); $actualposition =$pos + 1; //count strings $count =strlen($mystring); //count the number of characters for the first name $countfirstname = $actualposition - 1; //count the number of characters for the last name $countlastname = $count - $actualposition; //detect if full name has middle name $posmid= strpos($mystring,$findme,$actualposition) + 1; $middleadjust = $posmid - $actualposition; $purealpha = str_replace(" ", "x", $mystring); if ($actualposition==1) { echo 'ERROR: You either forgot your first name or your last name.'; die (); } if ($countfirstname <2) { echo 'ERROR: You are using an invalid first name, it should contain more than one character.'; die (); } if ($countlastname <2) { echo 'ERROR: You are using an invalid last name, it should contain more than one character.'; die (); } if ($middleadjust >= 2) { echo 'ERROR: You should not be using a middle name, please use only first name and last name.'; die (); } if (!(ctype_alpha($purealpha))) { echo 'ERROR: Full name can only consist of alphabetic characters.'; die (); } //Step 3.2 Validate phone number if (!(ctype_digit($phonenumber))) { echo 'ERROR: A phone number should consist of numerical digits only and no spaces between numbers'; die (); } //Step 3.3 Validate age if (!(ctype_digit($age))) { echo 'ERROR: Your age should consist of numerical digits only and no spaces between numbers'; die (); } //Step 4. If all data entry is correct, show results in another page, assigned all values to sessions echo 'Thank you for the correct data entry, below are the information entered:'; echo '<br />'; echo 'Your full name is: '.$name; echo '<br />'; echo 'Your phone number is: '.$phonenumber; echo '<br />'; echo 'Your age is: '.$age; echo '<br />'; echo '<a href="/ajaxwebform/ajaxwebformtest.php">Click here to enter another data.</a>'; $_SESSION = array (); session_destroy (); mysql_close($dbhandle); ?> Okay with some help I was able to create a working guestbook! How ever I need a bit of help with validation. I would like to have it so that when someone doesn't fill out a required field a message is displayed next to the improperly filled out field. How would I go about adding this to my form or process code? So for example: if someone doesn't fill out the "name" field and clicks "sign" it will not submit but instead will display a message such as "Please fill out your name" next to the form field. Also will I am here I wanted to ask. How can I make it so that when a non-required field is left empty and posted it will fill that section out with default text? So for example: if someone decides they do not wish to fill out the "Favorite part of my site" or "Favorite Pat Song" field than submits the form than it will fill that section with a default message like this: Posted by: someone (someone@domain.com) 2011/04/09 Favorite Pat Song: -- Favorite Part of the Site: -- comments here And I promise this is my very last question. I would like for email to be required but would like to allow the user to decide whether it is kept private or not. How do I make it so that when someone doesn't type their email in it does like what I stated above, it will show a message next to the field telling them to fill out a valid email but also if they select to keep their email private it will than post a default value in place of where the email would have been. for example: if the email field is left empty or is an invalid email it will display a message such as "Please fill out a valid email address" next to the form field. and than if they do so but also check the "private" box it will post their message in the guestbook with a default value in place of the email like this: Posted by: someone (Private) 2011/04/09 Favorite Pat Song: -- Favorite Part of the Site: -- comments here so that was a lot here's my guestbook code: Code: [Select] <?php <span style='color:#ff0000'><b>*</b></span><span> = required field</span><br /><br /> <form name='guestbook' action='process.php' method='post'> <table width='550' border='0' cellspacing='2' cellpadding='0'> <tr valign='top'> <td width='550px' class='what'><span style='color:#ff0000'><b>*</b></span> Your Name:</td> <td width='550px'><input name='name' type='text' id='name' size='32' /></td> </tr> <tr valign='top'> <td width='550px' class='what'><span style='color:#ff0000'><b>*</b></span> Email Address:</td> <td width='550px'><input name='email' type='text' id='email' size='32' /><input type='checkbox' name='private' value='Private' />Private</td> </tr> <tr valign='top'> <td width='550px' class='what'>Your Favorite Pat Song?:</td> <td width='550px'><input name='song' type='text' id='song' size='32' /></td> </tr> <tr valign='top'> <td width='550px' class='what'>Your Favorite Part of my Site?:</td> <td width='550px'><input name='part' type='text' id='part' size='32' /></td> </tr> <tr valign='top'> <td width='550px' class='what'><span style='color:#ff0000'><b>*</b></span> Comment:</td> <td width='550px'><textarea name='comments' cols='28' rows='6' id='comments' class='bodytext'></textarea></td> </tr> <tr> <td class='bodytext'> </td> <td align='left' valign='top'><input name='submit' type='submit' class='btn' value='Sign' /></td> </tr> </table> </form>"; }else{ $connect = mysql_connect("127.0.0.1","patben_admin","pepsi_1990") or die('Error connecting'); $db = mysql_select_db("patben_db") or die('Error selecting db'); $query = mysql_query("SELECT * FROM guestbook order by id desc"); $num_rows = mysql_num_rows($query); if($num_rows > 0) { //display entries while($row = mysql_fetch_array($query)){ echo ' <table> <tr> <td> <b>Posted by:</b> '.$row['name'].' ('.$row['email'].')<br /> <b>'.$row['date'].'</b><br /> <b>Favorite Pat Song:</b> '.$row['song'].'<br /> <b>Favorite Part of the Site:</b> '.$row['part'].' </td> </tr> <tr> <td> '.nl2br($row['comments']).' <hr /> </td> </tr> </table>'; } }else{ echo "No Entries... <a href='guestbook.php?page=sign'>Be the first!</a>"; } } ?> and here's the code that processes the form (separate file): Code: [Select] <?php if($_POST['submit']) { $connect = mysql_connect('127.0.0.1','patben_admin','pepsi_1990') or die('Error connecting'); $db = mysql_select_db('patben_db') or die('Error selecting db'); $date = date("Y-m-d"); $name = strip_tags($_POST['name']); $email = strip_tags($_POST['email']); $song = strip_tags($_POST['song']); $part = strip_tags($_POST['part']); $comments = nl2br($_POST['comments']); $query = mysql_query("insert into guestbook values('','$date','$name','$email','$song','$part','$comments')"); header("location: guestbook.php"); }else{ header("location: guestbook.php"); } ?> I have not added a section in my database for the check box so I am also unsure how to do that (if I need to). Any help would be greatly appreciated! Thank you |