I want to preface this question with the fact that I am a student and this is my first PHP class. So, the following question might be a bit novice...
Okay so the point of this program was for me to filter results from a form through regular expressions along with clean up the text area content...
Well as of right now, all works fine except for the strip_tags bit. I have it set to allow the tags <b> and <p>, and when I enter regular text into the text area, it returns perfectly. If I enter something such as <b>lucky</b> you, all that is returned is 'b'.
I'll post my code. If anyone can give me a hand, I'd love it. At this point I'm overly frustrated. I've studied the examples my instructor supplied (mine is almost identical) and I've looked throught the PHP.net manual and from what I read it should work...
The working code is at http://www.lampbusters.com/~beckalyce/prog3b.php
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'GET' )
{
echo <<<STARTHTML
<div class="content"><h1>Site Sign Up</h1>
<h3>Enter Information</h3>
<hr />
<form method="post" action="$_SERVER[PHP_SELF]">
<p>Full Name: <input type="text" name="fullName" size="30" /></p>
<p>Password: <input type="password" name="password" size="30" maxlength="12" /></p>
<p>Email: <input type="text" name="email" size="30"/></p>
<p>Tell us about yourself:<br />
<textarea name="aboutYou" rows="5" cols="40"></textarea><br />
<input type="submit" name="submitted" value="submit" /> <input type="reset" /></p>
</form></div>
STARTHTML;
}
elseif ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
$errors = array();
$dirtyName = $_POST['fullName'];
$filterName = '/(\w+ ?){1,4}/';
if (preg_match($filterName, $dirtyName, $matchName))
{
$cleanedName = ucwords(strtolower(trim(strip_tags(stripslashes($matchName[0])))));
}
else
{
$errors[] = "Enter a valid name. <br />";
}
$dirtyPass = $_POST['password'];
$filterPass = '/[a-zA-Z0-91##$%^&*]{8,12}/';
if (preg_match($filterPass, $dirtyPass, $matchPass))
{
$cleanedPass = $matchPass[0];
}
else
{
$errors[] = "Enter a valid password. <br />";
}
$dirtyEmail = $_POST['email'];
$filterEmail = '/^(?:\w+[.+-_]?){1,4}(?:\w+)#(?:\w+\.){1,3}\w{2,4}/';
if (preg_match($filterEmail, $dirtyEmail, $matchEmail))
{
$cleanedEmail = $matchEmail[0];
}
else
{
$errors[] = "Enter a valid email address. <br />";
}
$dirtyText = $_POST['aboutYou'];
$filterText = '/((\w+)[ ."\'?!,-]{0,3})+/';
if (preg_match($filterText, $dirtyText, $matchText))
{
$validText = $matchText[0];
$ignore = '<b><p>';
$notags = strip_tags($validText,$ignore);
$cleanedText = preg_replace('/fuck|shit|ass|bitch|android/i',"*****",$notags);
}
else
{
$errors[] = "Enter information about yourself. <br />";
}
if (count($errors) == 0)
{
echo <<<STARTHTML2
<div class="content"><h1>Site Sign Up</h1>
<h3>Verify your information</h3>
<hr />
Name: <span class="choices"> $cleanedName <br /></span>
Password: <span class="choices">$cleanedPass <br /></span>
Email: <span class="choices">$cleanedEmail <br /></span>
About you: <span class="choices">$cleanedText <br /></span>
STARTHTML2;
}
else
{
echo "<div class=\"content\">Please correct the following errors:<br />\n";
$errnum = 1;
foreach ($errors as $inderr)
{
echo "$errnum. $inderr";
$errnum++;
}
}
echo '<br />Back to Form';
echo '</div>';
echo '<p style="text-align: center">' . date('l, F d, Y') . '</p>';
}
?>
It doesn't look like your regular expression allows for the < and > characters, also, if it was meant to match the entire text, it should start with ^ and end with $, otherwise it will just match on a small section of the input as best it can according to the pattern which is likely what happened to simply return 'b' in $match[0] when supplying <b>TextHere
Related
This question already has answers here:
Posting input type file problem No Value posted
(2 answers)
Closed 3 years ago.
I'm working on a (supposedly) simple page and script to send an email with an attachment, but have run into a problem where the last value is not sent in POST. Danged if I can figure it out.
The HTML from the sending page is:
<form action="contact_reply.php" method="post" name="form1" required="required" id="form1" enctype="multipart/form-data" >
<p>
<input type="hidden" name="PageURL" value="<?php echo GetSelfURL() ?>" />
</p>
<p>Your Name<br />
<span id="sprytextfield1">
<input name="MSG_Name" type="text" required="required" id="MSG_Name" tabindex="1" size="70" maxlength="70" />
</span>
</p>
<p>Your Email Address<br />
<span id="sprytextfield2">
<input name="MSG_Email" type="text" required="required" id="MSG_Email" tabindex="2" size="70" maxlength="70" />
</span>
</p>
<p>Subject<br />
<span id="sprytextfield3">
<input name="MSG_Subject" type="text" required="required" id="MSG_Subject" tabindex="3" size="70" maxlength="70" />
</span>
</p>
<p>Message<br />
<span id="sprytextarea1">
<textarea name="MSG_Text" required="required" id="MSG_Text" cols="70" rows="5" tabindex="4"></textarea>
</span>
</p>
<?php
if ($Allow_Attachments)
{
?>
<p>Attachment (images only):
<input name="MSG_Attachment" type="file" id="MSG_Attachment" tabindex="5" accept="image/*" multiple >
</p>
<?php
}
?>
<p align="center">
<input
type="submit"
name="Contact_SendBtn"
id="Contact_SendBtn"
value="Submit"
tabindex="5"
vakue="send"
style="width:60px"/>
</p>
</form>
The php on the receiving end is:
function CheckMessageInfo()
{
global $MSG_Name, $MSG_Email, $MSG_Subject, $MSG_Text, $MSG_Attachment, $MSG_Error;
$MSG_Error = '';
echo "<p>".var_dump($_POST)."</p>";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["MSG_Name"]))
{
$MSG_Error .= "A name is required. ".PHP_EOL;
}
else
{
$MSG_Name = test_input($_POST["MSG_Name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$MSG_Name))
{
$MSG_Error .= "Only letters and spaces are allowed in the name. ".PHP_EOL;
}
}
if (empty($_POST["MSG_Email"]))
{
$MSG_Error .= "An email address is required. ".PHP_EOL;
}
else
{
$MSG_Email = test_input($_POST["MSG_Email"]);
if (!filter_var($MSG_Email, FILTER_VALIDATE_EMAIL))
{
$MSG_Error .= "Invalid email format. ".PHP_EOL;
}
}
if (empty($_POST["MSG_Subject"]))
{
$MSG_Error .= "A subject for the message is required. ".PHP_EOL;
}
else
{
$MSG_Subject = filter_var($_POST["MSG_Subject"],FILTER_SANITIZE_STRING);
}
if (empty($_POST["MSG_Text"]))
{
$MSG_Error .= "The message's text is required. ".PHP_EOL;
}
else
{
$MSG_Text = filter_var($_POST["MSG_Text"],FILTER_SANITIZE_STRING);
}
if (empty($_POST["MSG_Attachment"]))
{
$Allow_Attachments = FALSE;
}
else
{
$MSG_Attachment = $_POST["MSG_Attachment"];
}
return TRUE;
}
else
{
return FALSE;
}
}
The var_Dump line give me this:
array(6) {
["PageURL"]=> string(39) "www.vintagebankantiques.net/contact.php"
["MSG_Name"]=> string(4) "Mike"
["MSG_Email"]=> string(21) "me#myemail.com"
["MSG_Subject"]=> string(4) "test"
["MSG_Text"]=> string(21) "improved echo $_POST."
["Contact_SendBtn"]=> string(6) "Submit"
}
The "MSG_Attachment" variable is not listed. Where did it go?
You can get value of MSG_Attachment by
$_FILES['MSG_Attachment']["tmp_name"]
//if MSG_Attachment is array type
$_FILES['MSG_Attachment']["tmp_name"][0]
$_FILES['MSG_Attachment']["tmp_name"][1]
since MSG_Attachment input type is file, you can not get in POST.
you can also refer this link
I have a form and the action of the for m is same page.
I am trying to :
Show a thanks message upon the successful form submission
Show error messages next to the field where the error is detected
All the above must be shown in the same page.
My code is :
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
else {
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
?>
I've limited the validation and showing only for first part in this QUESTION.
When I submit this form If there is NO any errors the I am getting the message Thanks, We have received your feed back
That's fine and works as expected.
When an error exists / the field Guest name is empty I am getting the message during the form submission Errors!
Please check the fields which have errors below. Error hints are in Red.
That's also fine.
But my form is just disappear when I get the above message. Why?
Also I want show that Please type your name! next to the field.
Try bellow code. I have removed else part and set flag with true/false to check from is valid or not.
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
$chkValidate = "true";
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
$chkValidate = "false";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';
$chkValidate = "false";
}
if($chkValidate == "true"){
echo 'Thanks, We have received your feed back';
}
}
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?php if(!empty($errors) && $chkValidate != "false") { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
?>
Just remove else condition cause actually your form will not be display if $_POST["Ask_the_Question"] is set
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
The reason why is here:
<?php
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
} else {
// your form code will never be called if $_POST['Ask_the_Question'] is set
TO do what you want to achieve you probably want to do something like this instead:
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
} else { ?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
}
?>
Other answers are fine, but just to clarify what happens.
But my form is just disappear when I get the above message. Why?
Your form disappear because if you pass the first if you can't get to your else.
if (isset($_POST["Ask_the_Question"])) {
...
} else {
xxx;
}
That means if you want to see your form you have to put it somewhere it can be shown like elseif (with more restrictions), or ifs inner or outer.
if (isset($_POST["Ask_the_Question"]) && empty($errors)) {
...
} elseif (isset($_POST["Ask_the_Question"]) && !empty($errors)) {
...
} else {
...
}
Also I want show that Please type your name! next to the field.
To show all errors you could use eg. foreach anywhere you want to show them.
foreach ($errors as &$error) {
echo "Error: $error<br />\n";
}
Btw be careful with the empty(); function.
I am beginner in PHP and I want to check whether user has filled the input named "jmeno". Name of the corresponding variable is the same. If the input is not entered, then the variable "chybi" should be expanded by text "Zadej jméno!" and that text should appear above the form.
I am getting no errors. If the input is filled, then the form proceeds. If not, then the form doesn't proceed - that works how it's supposed to. But the error message in variable "chybi" doesn't display for some unknown reason in case that the variable "jmeno" is empty (second if).
I have tried many things. It's strange that such a simple script doesn't work. Any ideas? Thank you.
<?php
$chybi = '';
$zacatek = '
<p>some long text</p>
<form action="index.php" method="post" class="akce">
<p>' .$chybi.
'<input type="text" name="jmeno" placeholder="Zadej své jméno," /></p>
<p>
vyber pohlaví<br />
<input type="radio" name="pohlavi" value="žena" /> žena<br />
<input type="radio" name="pohlavi" value="muž" /> muž
</p>
<p>a pokud se nebojíš, <input type="submit" value="vstup!" /></p>
</form>
';
if ( isset($_POST['jmeno']) && isset($_POST['pohlavi']) ) {
$jmeno = $_POST['jmeno'];
$pohlavi = $_POST['pohlavi'];
if ( empty($jmeno) ) {
$chybi .= 'Zadej jméno!<br />';
echo $zacatek;
}
else {
echo "Jmenuješ se $jmeno a jsi $pohlavi.";
}
}
else {
echo $zacatek;
}
?>
As #jylipaa pointed out you're echoing $chybi before setting it's value. Move your logic above the $zacatek varaible.
<?php
$chybi = '';
if ( isset($_POST['jmeno']) && isset($_POST['pohlavi']) ) {
$jmeno = $_POST['jmeno'];
$pohlavi = $_POST['pohlavi'];
if ( empty($jmeno) ) {
$chybi .= 'Zadej jméno!<br />';
}
else {
echo "Jmenuješ se $jmeno a jsi $pohlavi.";
}
}
$zacatek = '
<p>some long text</p>
<form action="index.php" method="post" class="akce">
<p>' .$chybi.
'<input type="text" name="jmeno" placeholder="Zadej své jméno," /></p>
<p>
vyber pohlaví<br />
<input type="radio" name="pohlavi" value="žena" /> žena<br />
<input type="radio" name="pohlavi" value="muž" /> muž
</p>
<p>a pokud se nebojíš, <input type="submit" value="vstup!" /></p>
</form>
';
echo $zacatek;
?>
you are setting $zacatek in the start of code where $chybi is still empty. It is then handled as a string and setting the value of $chybi later on will not change the content of a string afterwards.
I have a form than when I submit incorrectly no error is displayed
<form action="emailSubs.php" method="post">
<p>Would you like to subscribe to our newsletter ?</p>
<p>Name: <input type="text" name="name"><br /></p>
<p>E-mail: <input type="text" name="Email"><br /></p>
<p><input type="submit" name="submit"><br /></p>
</form>
<?php
function validateEmail($data, $fieldName) {
global $errorCount;
if(empty($data)) {
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
} else { // olny clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\[[a-z]]{2,})$/i";
if(preg_match($pattern, $retval) ==0) {
echo "\"$fieldName\" is not a valid E-mail
address.<br />\n";
++$errorCount;
}
}
return ($retval);
}
?>
I think it may be the pattern but am not sure what the problem may be
The problem is that you do not have the two things connected properly...
Leave your form in a separate file from emailSubs.php -
While this is not a necessary step, it will hopefully help you understand the way this works (not to mention it is a much neater / organized way to do it)
<form action="emailSubs.php" method="post">
<p>Would you like to subscribe to our newsletter ?</p>
<p>Name: <input type="text" name="name"><br /></p>
<p>E-mail: <input type="text" name="Email"><br /></p>
<p><input type="submit" name="submit"><br /></p>
</form>
Now, in your emailSubs.php file :
<?php
function validateEmail($data, $fieldName) {
global $errorCount;
if(empty($data)) {
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
} else { // olny clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\[[a-z]]{2,})$/i";
if(preg_match($pattern, $retval) ==0) {
echo "\"$fieldName\" is not a valid E-mail
address.<br />\n";
++$errorCount;
}
}
return ($retval);
}
?>
But, you aren't done, yet -!
You see, you have to connect the two ---
In your form, you specified method="post" - so, we do this:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
?>
Now, there are plenty of good reasons to not use regexp to validate your form.
This is a good read on that topic.
So, what you might do instead, could look like this:
<?php
if(ctype_alnum($_POST['name']) == true){
$name = $_POST['name'];
} else {
exit("Please enter a valid name");
}
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL){
$email = $_POST['email'];
} else {
exit("Please enter a valid email address");
}
?>
And you see? That makes for a much cleaner way to handle your validation.
SO, Full circle, your code didn't display an error because there was nothing to display that error.
I noticed that you have a form, and a function but you don't call the function when the form is submitted. Maybe this is something you are doing outside the scope of the code you included, but just in case, I modified it to be a complete interaction between submission/function call and the form itself. Also, why not use filter_var instead of a regular expression?
Code (working on my local server):
<?php
function validateEmail($data, $fieldName)
{
global $errorCount;
$errorCount=0;
if(empty($data))
{
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
}
else
{
// olny clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
if(!filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL))
{
echo "\"".$_POST['Email']."\" is not a valid E-mail
address.<br />\n";
++$errorCount;
}
}
return ($retval);
}
if(isset($_POST['submit']))
{
$email=validateEmail($_POST['Email'], "Email");
if(empty($errorCount))
{
//create subscription
echo "Subscribed!";
}
}
?>
<form action="test.php" method="post">
<p>Would you like to subscribe to our newsletter ?</p>
<p>Name: <input type="text" name="name" value="<?php echo $_POST['name'];?>"><br /></p>
<p>E-mail: <input type="text" name="Email" value="<?php echo $_POST['Email'];?>"><br /></p>
<p><input type="submit" name="submit"><br /></p>
</form>
Please bear with me as I am a graphic designer with some coding knowledge, but not near as much as a developer. And after many hours of tinkering and asking Google, I've decided to ask y'all directly!
I've been working on building a contact form for my website. So far so good, except for one thing. I would like to add a simple spam prevention field.
I've added a field "spamcheck" with the question 6+2=? but I do not know how to code the PHP to require that the value specifically be 8. As long as the other fields are correctly filled out, the form will submit regardless of the number entered here despite any attempt to mess with the code (thus why you will see my $spamcheck variable but the current coding only requires that it have a value like the rest of the fields).
I have included the PHP, the validation the PHP calls to, and the form. Apologies if the form has some excess code; I have tried many different versions of PHP form tutorials to no avail.
And of course, thank you very much for your help! :)
Here is the PHP code I have placed directly in the web page:
<?php
define("EMAIL", "email#gmail.com");
if(isset($_POST['submit'])) {
include('validate.class.php');
//assign post data to variables
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$budget = trim($_POST['budget']);
$deadline = trim($_POST['deadline']);
$message = trim($_POST['message']);
$spamcheck = trim($_POST['spamcheck']);
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 1, 50);
$v->validateEmail($email, "email");
$v->validateStr($budget, "budget");
$v->validateStr($deadline, "deadline");
$v->validateStr($message, "message", 1, 1000);
$v->validateStr($spamcheck, "spamcheck");
if(!$v->hasErrors()) {
$from = "website.com"; //Site name
// Change this to your email address you want to form sent to
$to = "email#gmail.com";
$subject = "Hello! Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Budget: " . $budget ."
Deadline: " . $deadline ."
Message: " . $message ."";
mail($to,$subject,$message,$from);
//grab the current url, append ?sent=yes to it and then redirect to that url
$url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header('Location: '.$url."?sent=yes");
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
$nameErr = $v->getError("name");
$emailErr = $v->getError("email");
$budgetErr = $v->getError("budget");
$deadlineErr = $v->getError("deadline");
$messageErr = $v->getError("message");
$spamcheckErr = $v->getError("spamcheck");
}//end error check
}// end isset
?>
This is the validate.class.php which it calls to:
<?php
class validate {
public $errors = array();
public function validateStr($postVal, $postName, $min = 1, $max = 1000) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." is required.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, "Please enter an Email Address");
} else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
$this->setError($emailName, "Please enter a Valid Email Address");
}
}// end validateEmail
private function setError($element, $message) {
$this->errors[$element] = $message;
}// end logError
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}// end getError
public function displayErrors() {
$errorsList = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errorsList .= "<li>". $value . "</li>\n";
}
$errorsList .= "</ul>\n";
return $errorsList;
}// end displayErrors
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}// end hasErrors
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = "There was an error sending your message!\n";
} else {
$message = "There was an error sending your message!\n";
}
return $message;
}// end hasErrors
}// end class
?>
And here is the form html/php:
<span class="message"><?php echo $message_text; ?></span>
<?php if(isset($_GET['sent'])): ?><h2>Your message has been sent</h2><?php endif; ?>
<form role="form" method="post" action="webpage.php#contact">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" value="<?php echo htmlentities($name); ?>" placeholder="Full Name" required>
<label for="exampleInputName"><i class="icon-tag"></i></label>
<span class="errors"><?php echo $nameErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" id="email" value="<?php echo htmlentities($email); ?>" placeholder="Email" required>
<label for="exampleInputEmail1"><i class="icon-inbox"></i></label>
<span class="errors"><?php echo $emailErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="text" name="budget" class="form-control" id="budget" value="<?php echo htmlentities($budget); ?>" placeholder="Budget" required>
<label for="exampleInputBudget1"><i class="icon-usd"></i></label>
<span class="errors"><?php echo $budgetErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="text" name="deadline" class="form-control" id="deadline" value="<?php echo htmlentities($deadline); ?>" placeholder="Deadline" required>
<label for="exampleInputDeadline"><i class="icon-calendar"></i></label>
<span class="errors"><?php echo $deadlineErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group textarea">
<textarea rows="6" name="message" class="form-control" id="message" value="<?php echo htmlentities($message); ?>" placeholder="Write Message" required></textarea>
<label for="exampleInputMessage"><i class="icon-pencil"></i></label>
<span class="errors"><?php echo $messageErr; ?></span>
<div class="clearfix"></div>
</div>
<div class="form-group">
<input type="text" name="spamcheck" class="form-control" id="spamcheck" value="<?php echo htmlentities($spamcheck); ?>" placeholder="Spam check: 6+2=?" required>
<label for="exampleInputSpamCheck"><i class="icon-lock"></i></label>
<span class="errors"><?php echo $spamcheckErr; ?></span>
<div class="clearfix"></div>
</div>
<button type="submit" id="submit" name="submit" value="submit" class="btn btn-large">Send Message</button>
</form>
In the PHP script where you generate the form, you should save the correct answer to the question in a $_SESSION variable.
Then, in the PHP script that receives this form data, you should verify that what was submitted for that question matches the right answer in the $_SESSION variable.
There are a bunch of tutorials on how to use sessions in PHP.
Basically, it comes down to:
form.php
<?php
session_start();
$_SESSION['captcha_right_answer'] = somehow_generate_this();
?>
handler.php
<?php
session_start();
if ($_INPUT['captcha_answer'] != $_SESSION['captcha_right_answer']) {
// Show "bad captcha" message, re-show form, whatever
}
else {
// Captcha good - go on with life
}
?>
Check this out as an alternative to a captcha. Then you could use your existing class to validate the field. Say your hidden field has a name "fakeField" You could validate it with your validateSTR method via..
$v->validateStr($fakeField, "fakeField",0,0);
Since your str check is checking > and < instead of >= and <= this will return true when the length is exactly 0. This might be an easier solution for someone with little code knowledge to integrate.
Alternatively, if you're stuck on using a captcha of sort, and you know what you expect the value to be, you could add a method to check against the value you're expecting.
The method:
public function validateCaptcha( $value,$name, $expectedValue) {
if(trim($value) != $expectedValue) {
$this->setError($name, "Captcha Incorrect");
}
}
then change the line of code
$v->validateStr($spamcheck, "spamcheck");
to
$v->validateCaptcha($spamcheck, "spamcheck", '6');
This isn't the best solution since there are so many powerful captchas out therebut it's easy to use.
Another simple method is to capture the time the page loads and compare it to the time the form was submitted. If the difference was too short, exit the page. spambots are quick; people are slow. Spambots may figure out various fields - even do math - but they are never going to wait around for more than a few seconds.
It takes only two lines, one in the form:
<input name="timeloaded" type="hidden" value="<?php echo time();?>" />
and one in the form processing code:
if(!(is_numeric($_POST['timeloaded'])) || time()-$_POST['timeloaded']<30) {header("Location: index.php"); exit;}
This one is for a form that no human can fill out in less than 30 seconds. Change that for the length of form you use.