I am fairly new to PHP and a new student and so I will ask in advance to please forgive me if I have made errors that will be clearly obvious to someone experienced.
I am working on a page submission form that connects to a mysql database to either check for an existing value and if it does not exist then logs a string value of the datetime picker and also appends an id number to make a unique value to a table whenever someone was to press submit, and after form validation is accepted. Submitting if the record does not exist works and is ok.
However, whenever a record already exists, rather than displaying in the error message that the time is unavailable, the entire page just goes blank.
Initially, I had a button that would check to see if the record existed in the mysql table but I then decided it would be more efficient to try to include the date validation check of mysql table while completing the form validation and this is where I have trouble and of course the page breaks and nothing is displayed.
If someone could please guide me I would be most grateful.
it seems I am unable to add more code, but I will add what was wrong.
I did need to initialize $error=''; also $DateTime, and $id at the top of the script, I had it below but had forgotten to place it above and that was causing my problem.
<?php
$userid = "1";
$strid = strval($id);
$DateTimeCheck = $DateTime . $strid;
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->exec("SET CHARACTER SET utf8");
$sql = "SELECT booked FROM user_booking WHERE `booked` = :booked";
$sqlprep = $con->prepare($sql);
$ar_val = array(':booked' => $DateTimeCheck);
if (isset($_POST['datetime'])){
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
if (!$_POST['email']) {
$error .= "<br/>- Please enter your email";
}
if (!$_POST['message']) {
$error .= "<br/>- Please enter a message";
}
if (!$_POST['check']) {
$error .= "<br/>- Please confirm you are human";
}
if ($sqlprep->execute($ar_val)) {
while ($row = $sqlprep->fetch(PDO::FETCH_OBJ)) {
$DateTimeExists = $row->booked;
}
}
if (isset($DateTimeExists) && $DateTimeExists != ''){
$error .= "<br/>- The time you have requested is unavailable";
}
if ($error) {
$result = '<div class="alert alert-danger" role="alert"><strong>Whoops, there is an error</strong>. Please correct the following: ' . $error . '</div>';
} else {
mail("#gmail.com", "Contact message", "Name: " . $_POST['name'] . "
Email: " . $_POST['email'] . "
When: " . $_POST['datetime'] . "
Message: " . $_POST['message']);
{
$result = '<div class="alert alert-success" role="alert">Thank you, someone will be in touch soon to confirm your appointment. </div>';
$id = "$userid";
$strid = strval($id);
$DateTime = $_POST['datetime'];
$DateTimeCheck = $DateTime . $strid;
$strid = strval($id);
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_booking ( user_id, booked ) VALUES ( :id, :booked )";
$q = $con->prepare($sql);
$q->execute(array(':booked' => $DateTime . $strid,
':id' => $id));
$con = null;
}
}
}
?>
Here is the markup for the form.
<form method="post" role="form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your name"
value="<?php echo $_POST['name']; ?>">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your email"
value="<?php echo $_POST['email']; ?>">
</div>
<div class="form-group" align="left">
<label class="control-label">Date/Time</label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' name="datetime" class="form-control" placeholder="desired time"
value="<?php echo $_POST['datetime']; ?>">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<textarea name="message" rows="5" class="form-control"
placeholder="message..."><?php echo $_POST['message']; ?></textarea>
</div>
<div class="checkbox" align="left">
<label class="readable" align="left">
<input type="checkbox" name="check"> I am human
</label>
</div>
<div align="left">
<input type="submit" name="submit" class="btn btn-success" value="Book Appointment!"/>
</div>
</form>
If you are using .= you need to first initialise the variable before .= will work on the variable.
You attempted to do that in this IF block
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
but if that error is not present you will never actually initialise the $error variable.
So the simple solution is to initialise $error before getting into this section of code
$error = '';
if (isset($_POST['datetime'])){
// So now you can change this test to use .=
if (!$_POST['name']) {
$error .= "<br/>- Please enter your name";
}
Now the variable will be testable later in the code
If this is in fact the problem here, you should have been getting errors reported. If you didnt see any then try adding these lines of code to any problem script while you test it
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Related
This question already has an answer here:
PHP PDO prepared statements
(1 answer)
Closed 1 year ago.
I am using PHP and PDO, the problem is when I click on the submit button the data is not inserted into the Database. There are no errors at all, I am not sure what's causing it. I've tried a lot of things and still can't manage to find a solution.
This is my code:
<?php
function cl($info){
return preg_replace("|[^\w]|", "", $info);
}
function cl2($info){
return preg_replace("|[^\w]|", "", $info);
}
function check_email($email){
$exit = FALSE;
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
return $exit = TRUE;
}
else {
return $exit;
}
}
if (isset($_POST['register'])) {
$errors = [];
$username = cl($_POST['username'] ?? '');
$password = cl2($_POST['password'] ?? '');
$email = $_POST['email'] ?? '';
try {
$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
$check_username = $conn->prepare("SELECT * FROM accounts WHERE name = :username");
$check_username->bindParam(':username', $username, PDO::PARAM_STR);
$check_username->execute();
if($check_username->rowCount()) {
array_push($errors, 'Username already in use, please select a new one.');
} else if(empty($username) || strlen($username) < 4 || strlen($username) > 13) {
array_push($errors, 'Invalid username, please select another one.');
} else if(empty($password) || strlen($password) < 4 || strlen($password) > 20) {
array_push($errors, 'Invalid password, please select another one.');
} else if(empty($email) || !check_email($_POST['email'])) {
array_push($errors, 'Invalid password, please select another one.');
}
if(empty($errors)) {
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES ($username,$password,$email)");
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->execute();
echo '<br />';
echo ' <div class="alert alert-success text-center" role="alert">
Account created succesfully.
</div>';
} else {
foreach($errors as $error) {
echo '<br />';
echo '<div class="alert alert-danger text-center" role="alert">';
echo $error;
echo '</div>';
}
}
}
?>
And the form:
<form method="POST">
<div class="form-group">
<label for="InputUsername">Username</label>
<input type="text" class="form-control" id="InputUsername" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="password">
</div>
<div class="form-group">
<label for="inputEmail">Email address</label>
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" name="email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="rules">
<label class="form-check-label" for="rules">I have read the rules before creating a new account.</label>
</div>
<br />
<button type="submit" class="btn btn-primary" name="register">Submit</button>
</form>
I am trying this using Wamp, in a local development. If anyone could help me I would really appreciate it.
Okay now after adding this to my code:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I am getting the following error:
Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.accounts' doesn't exist
But the table exists in my db. This is acting weird.
From what I can see this line is wrong
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES ($username,$password,$email)");
It should be
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES (:username,:password,:email)");
I THINK it would've worked had you put quotes around the variables but you look like you want to prevent sql injection properly.
I created this signup page. The problem is when I click submit after I enter the information nothing happens. It just refreshes the same page. The info I enter should import into my database after I hit submit and display a thank you for signing up message after the submission. Please help. I'm trying to keep everything to single page by implementing the html and php code all on one page instead of 2 separate files.
<html>
<body>
<?php
$output_form = true; //declare a FLAG we can use to test whether or not to show form
$first_name = NULL;
$last_name = NULL;
$email = NULL;
if (isset($_POST['submit']) ) { //conditional processing based on whether or not the user has submitted.
$dbc = mysqli_connect('localhost', 'name', 'pswd', 'database')
or die('Error connecting to MySQL server.');
$first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$output_form = false; // will only change to TRUE based on validation
//Validate all form fields
if (empty($first_name)) {
echo "WAIT - The First Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($last_name)) {
echo "WAIT - The Last Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($email)) {
echo "WAIT - The Email field is blank <br />";
$output_form = true; // will print form.
}
if ((!empty($first_name)) && (!empty($last_name)) && (!empty($email))) {
//End of form validation
//This section establishes a connection to the mysqli database, and if it fails display error message
$query = "INSERT INTO quotes (first_name, last_name, email, " .
"VALUES ('$first_name', '$last_name', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
$to = 'email#email.com';
$subject = 'New Customer';
$msg = "$first_name $last_name\n" .
"Email: $email\n";
$mail = mail($to, $subject, $msg, 'From:' . $email);
if($mail){
header("Location: https://www.locate.com/blue.php".$first_name);
exit();
}
//Display the user input in an confirmation page
echo "<body style='margin-top: 100px; background-color: #f2f0e6;'><p style = 'color: #000000; text-align: center;font-size:300%; font-family:Arial, Helvetica, sans-serif;'><strong>Thanks for signing up!</strong></p><center><p style = 'color: #000000; text-align: center;font-size:200%; font-family:Arial, Helvetica, sans-serif;'>Contact us for any questions
</p>
</center>
</body>";
}//end of validated data and adding recored to databse. Closes the code to send the form.
} //end of isset condition. This closes the isset and tells us if the form was submitted.
else { //if the form has never been submitted, then show it anyway
$output_form = true;
}
if ( $output_form ) { //we will only show the form if the user has error OR not submitted.
?>
<div id="box">
<center><img src="../../images/duck.jpg" class="sign-up" alt="Sign Up"></center>
<br>
<p>Sign Up to get Discount Code</p><br>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<div>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" size="37" maxlength="37" value=" <?php echo $first_name; ?>" />
</div>
<div>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" size="37" maxlength="37" value="<?php echo $last_name; ?>" />
</div>
<div>
<label for="email">Email:</label>
<input type="text" id="email" name="email" size="37" maxlength="37" value="<?php echo $email; ?>" />
</div>
<div id="submit">
<input type="submit" name="Submit" value="Submit" />
</div>
</center>
</form>
</div>
<?php
}
?>
</body>
You are asking for $_POST['submit'] instead of $_POST['Submit']
I'm trying to input form data into the database. I'm using almost the same code as I did for my registration script, which works perfectly. I'm completely stumped at this point.
I have error reporting turned on for PHP and PDO, nothing is happening. When the form is sent, it appears to work (except without the confirmation messages appearing) but nothing is entered into the database.
I have two files, request.php (the form) and parseRequest.php (the backend to the form).
request.php
<form action="" method="post">
<div class="form-group">
<input type="hidden" class="form-control" name="username" id="usernameField" value="<?php echo $_SESSION['username'];?>">
</div>
<div class="form-group">
<label>Headlining Band/Artist</label>
<input type="text" class="form-control" name="artist" id="artistField" placeholder="Artist">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="day" id="dateField" placeholder="MM/DD/YYYY">
</div>
<div class="form-group">
<label>Venue</label>
<input type="text" class="form-control" name="venue" id="venueField" placeholder="Venue">
</div>
<div class="form-group">
<label>City, State</label>
<input type="text" class="form-control" name="city" id="cityField" placeholder="City, State">
</div>
<input type="hidden" name="token" value="<?php if(function_exists('_token')) echo _token(); ?>">
<button type="submit" name="requestBtn" class="btn btn-primary pull-right">Submit</button>
parseRequest.php
<?php
include_once 'resource/Database.php';
include_once 'resource/utilities.php';
include_once 'resource/send-email.php';
// Processing the form
if(isset($_POST['requestBtn'], $_POST['token'])){
if(validate_token($_POST['token'])) {
//process form here
$form_errors = "";
// validation
$required_fields = array('artist', 'day', 'venue', 'city');
// check empty fieldset
$form_errors = check_empty_fields($required_fields);
// date check
$fields_to_check_length = array('day' => 10);
//call the function to check minimum required length and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// collect data
$username = $_POST['username'];
$artist = $_POST['artist'];
$day = $_POST['day'];
$venue = $_POST['venue'];
$city = $_POST['city'];
}
else if(empty($form_errors))
{
// preparing and inputting data
try
{
$sqlInsert = "INSERT INTO requests(username, artist, day, venue, city)
VALUES (:username, :artist, :day, :venue, :city)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':username' => $username, ':artist' => $artist, ':day' => $day, ':venue' => $venue, ':city' => $city));
// email confirmation
$addresses = array($_SESSION['email'], 'codylkaczynski#gmail.com');
//prepare email body
$mail_body = '<html>
<body style="font-family: Arial, Helvetica, sans-serif;
line-height:1.8em;">
<h2>Amped Sound Staff Portal: Request Received</h2>
<p>Dear '.$username.'<br><br>
Your request for the '.$artist.' show in '.$city.' on '.$date.' has been received!</p><br/>
<p>We will let you know if your request has been approved or denied ASAP.</p><br/>
<p>Thank you!</p><br/>
<p><strong>©2018 Amped Sound</strong></p>
</body>
</html>';
$namejeff = explode(',', $addresses);
foreach ($addresses as $address)
{
$mail->AddAddress($address);
$mail->Subject = "Request Received!";
$mail->Body = $mail_body;
}
//Error Handling for PHPMailer
if(!$mail->Send())
{
$result = "<script type=\"text/javascript\">swal(\"Error\",\" Email sending failed: $mail->ErrorInfo \",\"error\");</script>";
}
else
{
$result = "<script type=\"text/javascript\">
swal({
title: \"Request received!\",
text: \"We have received your request! Please check your email for confirmation.\",
type: 'success',
confirmButtonText: \"Thank You!\" });
</script>";
}
}
catch (PDOException $ex)
{
$result = flashMessage("An error occurred: " .$ex->getMessage());
}
}
}
I appreciate any help I can get. I've tried a bunch of solutions I found on StackOverflow already, to no avail.
I am working on a code right now that allows for the user to input their email and another user's email to add them as a "friend" into the table "friends"
So far my code works in terms of posting the form data into the DB / table "friends" however the message I would like to appear is not showing up at all.
My HTML form:
<form class="form-signin" action="FriendLookup.php" method = "POST" enctype="multipart/form-data">
<h2 class="form-signin-heading">Add a Friend</h2>
</br>
<label for="inputEmail" class="sr-only">Your Email</label>
<input type="text" id="inputEmail1" name = "self_email" class="form-control" placeholder="Friend's Username" >
</br>
<label class="sr-only">Your Friend's Email</label>
<input type="text" id="inputEmail2" name = "friend_email" class="form-control" placeholder="Your Username" >
</br>
<button class="btn btn-lg btn-primary btn-block" name = "submit" type="submit">Search</button>
</form>
PHP script:
<?php
include_once('support.php');
//connect_database.php contains your connection/creation of a PDO to connect to your MYSQL db on bmgt406.rhsmith.umd.edu/phpmyadmin
include_once('connect_database.php');
ini_set("display_errors","1");
error_reporting(E_ALL);
// Initialize $title and $body.
$title = "Add User";
$body = "<fieldset><legend> $title </legend>";
$name_of_table = "friends";
// Check if the table exists in the db.
if (tableExists($db, $name_of_table)) {
$inputemail1 = $_POST['self_email'];
$inputemail2 = $_POST['friend_email'];
// Prepare a SQL query and bind all 6 variables.
$sqlQuery = "INSERT INTO $name_of_table ( self_email, friend_email)
VALUES ( :self_email, :friend_email)";
$statement1 = $db->prepare($sqlQuery);
$statement1->bindValue(':self_email', $inputemail1, PDO::PARAM_STR);
$statement1->bindValue(':friend_email', $inputemail2, PDO::PARAM_STR);
// Execute the SQL query using $statement1->execute(); and assign the value
// that is returned to $result.
$result = $statement1->execute();
if(!$result) {
// Query fails.
$body .= "Inserting entry for friend failed.";
} else {
// Query is successful.
$body .= "Success";
}
// Closing query connection
$statement1->closeCursor();
}
$body .= "</fieldset>";
echo generatePage($title,$body);
?>
Any help is greatly appreciated. I am a novice programmer.
My function generatePage was wrong. I added HTML into the function and now it works!
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.