I have the following error:
Notice: Undefined index: submit in C:\wamp\www\registration\register.php on line 6
Can't seem to work out whats wrong??? Here's the code::
<?php
//Create registration form (register.php)
include "../includes/db_connect.php";
if(!$_POST['submit']) ///Line 6
{
?>
<html>
<head><link rel="stylesheet" href="style.css"></head>
<div class="divider">
<strong>Register</strong><br/><br/>
<form method="post" action="register.php">
<div class="formElm">
<label for="first">First Name</label>
<input id="first" type="text" name="first">
</div>
<div class="formElm">
<label for="last">Last Name</label>
<input id="last" type="text" name="last">
</div>
<div class="formElm">
<label for="username">Desired Username</label>
<input id="username" type="text" name="username">
</div>
<div class="formElm">
<label for="password">Password</label>
<input id="password" type="password" name="password">
</div>
<div class="formElm">
<label for="pass_conf">Confirm Password</label>
<input id="pass_conf" type="password" name="pass_conf">
</div>
<div class="formElm">
<label for="email">Email</label>
<input id="email" type="text" name="email">
</div>
<div class="formElm">
<label for="about">About</label>
<textarea id="about" cols="30" rows="5" name="about">Tell us about yourself</textarea>
</div>
<input type="submit" name="submit" value="Register">
</form>
or Login
</div>
</html>
<?php
}
else
{
$first = protect($_POST['first']);
$last = protect($_POST['last']);
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$pass_conf = protect($_POST['pass_conf']);
$email = protect($_POST['email']);
$about = protect($_POST['about']);
$errors = array();
$regex = "/^[a-z0-9]+([_\.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+\.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
$errors[] = "E-mail is not in name#domain format!";
}
if(!$first || !$last || !$username || !$password || !$pass_conf || !$email || !$about)
{
$errors[] = "You did not fill out the required fields";
}
$sql = "SELECT * FROM `users` WHERE `username`='{$username}'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) == 1)
{
$errors[] = "Username already taken, please try another";
}
if(count($errors) > 0)
{
echo "The following errors occured with your registration";
echo "<font color=\"red\">";
foreach($errors AS $error)
{
echo "<p>" . $error . "\n";
}
echo "</font>";
echo "Try again";
//we use javascript to go back rather than reloading the page
// so the user doesn't have to type in all that info again.
}
else
{
$sql = "INSERT into `users`(`first`,`last`,`username`,`password`,`email`,`about`)
VALUES ('$first','$last','$username','".md5($password)."','$email','$about');";
$query = mysql_query($sql) or die(mysql_error());
echo "Thank You for registering {$first}! Your username is {$username}";
echo " Click here to Login";
}
}
?>
If there is no POST parameter at all or if there is no parameter named submit then you're trying to access an array index that does not exists, hence the warning. You can simply test if there is such an index/element in the _POST array.
if( isset($_POST['submit']) )
It doesn't check the value (like you original script, which tests if the value of _POST['submit'] equals false, see type juggling), but the mere existence of the index/element should suffice in this case.
see http://docs.php.net/isset
To get rid of this error, it should be:
if(!isset($_POST['submit']))
However, your code is already OK.
What you are getting is not an error, it is a warning, which is caused by having strict warnings enabld. PHP is a dynamic language which does not usually require to define variables and array keys, and most documentation and code will skip this part. So you should consider turning this feature off, as it clutters code and has few additional benefits. Or, switch to a statically compiled language (say asp.net) which will really benefit from defined variables and static typing.
Your $_POST does not exist when you first load your page. Change your check to something like:
if(!isset($_POST["submit"]))
Because you did not post anything yet, there will be no "submit" key in your $_POST array. That's what causes the warning.
For those posting use if(isset($_POST['submit'])), you clearly did not read his code. He has put is there is not a submit write the HTML form else use the fields (backwards righting to me!)
If he wants to keep the structure as is, it should be
if(empty($_POST['submit']))
Related
<?php
$fp = fopen("users.txt", "w");
if(!$fp) die ("Errore nella creazione dell'utente");
$fp=fwrite($email $password);
fclose($fp);
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
if($_SERVER["REQUEST_METHOD"]=="POST"){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = = htmlspecialchars($_POST["nazionalita"]);
}
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
header("location: index.php");
?>
But of course, this doesn't work.
How can I save to a specific location with PHP?
Then I'll have to do an explode which will only get my email and password. on the login.php page.
Thank you.
I'm not going to fix your code for you, but give you three tips:
Think like a computer. The computer is going to run your program one statement at a time, in the order you've written them; so if you have a line that writes a variable to a file, it needs to come after the line where you've put a value into that variable. It is also going to do exactly what you ask it, not guess what you meant, and not let you get away with typos; read your code back carefully.
Make use of the PHP manual. If you type in https://php.net/ followed by the name of a built-in function, like https://php.net/fwrite, you will get a page that explains what the input and output of that function is. Often, there are examples which show various ways of using the function, which you can use as inspiration for how to write your own code.
Turn on the display_errors setting, or learn where your log file is. Most of the mistakes in the code you show will result in errors or warnings, telling you exactly which line you need to look at. Read the messages carefully, and they'll often point out exactly what you've done wrong.
If you want to write to the file you could do $fpw = fwrite($fp,$email.' : '.$password);
you should pass the $fp to fwrite() method as follow
$fp = fopen('user.txt', 'w+') or die('Unable to open file!');
$fp=fwrite($fp, $email.'~'.$password.'\n'); // make sure to choose whatever seperator suits your need and be careful when choosing it
fclose($fp);
Thanks everyone, I fixed my code!!!
Following the correct code!
<?php
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
//$fp = fopen("users.txt", "w");
//$fpw = fwrite($fp,$dati $email.' : '.$password);
//fclose($fp);
if(isset($_POST["submitPut"])){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = htmlspecialchars($_POST["telefono"]);
$dati= "\n". $name . ",". $surname .",".$email.",". $password . ",". $nazionalita. ",". $telefono;
$file= fopen("users.txt", "a+");
$credenziali=fwrite($file, $dati);
fclose($file);
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
}
//header("location: index.php");
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once "views/head.php" ?>
<body>
<?php include_once "views/navbar.php" ?>
<main>
<div class="container my-5">
<h2>Registration user</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" >
</div>
<div class="form-group">
<label for="surname">surname:</label>
<input type="text" class="form-control" id="surname" name="surname" placeholder="Enter surname" >
</div>
<div class="form-group">
<label for="email">email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" >
</div>
<div class="form-group">
<label for="password">password:</label>
<input type="text" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="form-group">
<label for="nazionalita">nazionalita:</label>
<input type="text" class="form-control" id="nazionalita" name="nazionalita" placeholder="Enter nazionality" >
</div>
<div class="form-group">
<label for="telefono">telefono:</label>
<input type="text" class="form-control" id="telefono" name="telefono" placeholder="Enter phone" >
</div>
<button type="submit"name="submitPut" class="btn btn-primary">Submit</button>
</form>
</div>
</main>
<?php include_once "views/footer.php" ?>
<?php include_once "views/scripts.php" ?>
</body>
</html>
I'm having a issue where a variable is becoming undefined when the page is loaded individually...
So.
My front page has a address form where when the address is filled out and you click "Get your offer" it'll take you to another page where the address is carried over using $_POST['address'] in the value of the new input. so value="<?php echo $_POST['address']; ?>"
My problem is that when the offer page is loaded without using the front page form it gives me the error
<br /><b>Notice</b>: Undefined index: address in <b>C:\xampp\htdocs\offer\index.php</b> on line <b>228</b><br />Address
which makes sense. so i tried to fix it by putting this in the value= :
<?php
$carryover = $_POST['address'] or empty($carryover);
if(empty($carryover)) {
echo 'Enter Address';
} else {
echo $carryover;
}
?>
which did absolutely nothing so.
Front page form:
<form method="post" action="/offer/index.php" name="front" id="front">
<div class="form-group">
<input type="text" id="autocomplete" onFocus="geolocate()" name="address" id="address" value="" placeholder="123 main st" required>
<button type="submit" class="theme-btn btn-style-nine"><span class="txt">Get your offer</span></button>
</div>
</form>
Form 2 on offer page (where address is carried over too):
<form class="multisteps-form__form" action="finish.php" id="wizard" method="POST" enctype="multipart/form-data">
<div class="col-lg-8">
<div class="form-input-inner position-relative has-float-label" >
<input type="text" name="address" id="address" placeholder="Address" value="<?php
$carryover = $_POST['address'];
if(empty($carryover)) {
echo 'Address';
} else{
echo $carryover;
}
?>
" class="form-control" required>
<label>Address</label>
<div class="icon-bg text-center">
<i class="fas fa-home"></i>
</div>
</div>
</div>
</form
The undefined index notice happens when you read $_POST['address'] so any code you write after that isn't going to affect the notice.
Checking whether $carryover is empty is too late, you need to check if the $_POST index itself is empty.
Instead of:
$carryover = $_POST['address'];
if(empty($carryover)) {
echo 'Enter Address';
} else {
echo $carryover;
}
You need to use:
if(empty($_POST['address']) {
echo 'Enter Address';
} else {
$carryover = $_POST['address'];
echo $carryover;
}
Instead of this:
$carryover = $_POST['address'] or empty($carryover);
use this:
$carryover = $_POST['address'] ?? '';
i make a login system using php with json file data. i tried to login with JavaScript file and it works fine. but it is not secure well. then i change some code with php login.
this is my php code
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
$jsonemail = $value['email'];
$jsonpass = $value['pass'];
}
if($email == $jsonemail && $pass == $jsonpass){
header('location: view.php');
}
else{
echo "please check your email or password";
}
}
but this not working. i want to fix this code. i want to check email and password is correct with json file data.
this is my login.json file data like
"1": {
"email": "test123#gmail.com",
"pass": "123"
},
and this is my html login form
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp" required="require" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pass">Password</label>
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" name="submit" >Submit</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
</div>
I think your email and pass variable are not defined. Have a look at it.
if (isset($_POST['submit'])) {
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
$email = $_POST['email']; // I think you miss this
$pass = $_POST['pass']; // and this lines as in your code its missing
$flag = false;
foreach ($parsed_json as $key => $value) {
if ($value['email'] == $email && $value['pass'] == $pass) {
$flag = true;
break;
}
}
if ($flag) {
header('location: view.php');
} else {
echo "Please check your email and password."
}
}
And one more thing
while posting any form you must name element which you want in $_POST.
<input type="password" class="form-control" id="pass" required="require" placeholder="Password">
In above line you are missing name as pass. Replace above line with
<input type="password" class="form-control" id="pass" required="require" placeholder="Password" name="pass">
This should solve your problem.
Your foreach is just overwriting the values of $jsonemail and $jsonpass each time, so when you reach the if() part to check the user details, these will always be the last values in the file.
if(isset($_POST['submit'])){
$json_string = file_get_contents('login.json');
$parsed_json = json_decode($json_string, true);
foreach($parsed_json as $key => $value){
if($email == $value['email'] && $pass == $value['pass']){
header('location: view.php');
exit();
}
}
echo "please check your email or password";
}
This code redirects if the user is found and if it gets to the end of the loop, then the user doesn't exist in the file.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Goodday house,i'm developing this site that has a registration/login page as my first project and i'm stucked right now.
I added php validation to my registration form but the database insert statement refuses to work after,though all conditional statements were fulfilled,i tried putting a redirect loop immediately after the insert statement but my script automatically (somehow) jumps the "Insert statement" and processes the redirect code..
This is the code below
<!-- Php validation-->
<?php
include 'var.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Starts an array to store errors.
//Validation rules involves trimming,validating and sanitizating
$name = trim($_POST['name']);
$strippedname = mysqli_real_escape_string($con, strip_tags($name)) ;
$length = mb_strlen($strippedname, 'utf-8') ;
if ($length < 8 ) {
$errors[]= 'Your full name shouldn\'t be less than 8 letters' ;
} else {
$name = $strippedname ;
}
$email = FALSE ;
if (empty($_POST['email'])) {
$errors[] = 'You didn\'t provide any email address' ;
} // Next is removal of spaces and validation.
if (filter_var((trim($_POST['email'])), FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string($con, (trim($_POST['email'])));
}
else {
$errors[] = 'Email address was provided in the wrong format';
}
$pho = trim($_POST['phone']) ; // next line of code removes all characters that aren't digits
$phon = preg_replace('/\D+/', '', ($_POST['phone']));
$strippedphone = mysqli_real_escape_string($con, strip_tags($phon));
$length = mb_strlen($strippedphone, 'utf-8') ;
if ($length <> 11 ) {
$errors[] = 'Phone number should contain only eleven digits';
}
else {
$phone = $strippedphone ;
}
$add = trim($_POST['address']) ;
$strippedadd = mysqli_real_escape_string($con, strip_tags($add)) ;
$length = mb_strlen($strippedadd, 'utf-8') ;
if ($length < 15) {
$errors[]= 'Address should not be lesser than 15 letters' ;
} else {
$address = $strippedadd ;
}
if (empty($_POST['gender'])) {
$errors[] = 'You didn\'t select a gender';
} else {
$gend = trim($_POST['gender']);
}
$user = trim($_POST['username']);
$strippeduser = mysqli_real_escape_string($con, strip_tags($user)) ;
$length = mb_strlen($strippeduser, 'utf-8') ;
if ($length < 6) {
$errors[] = 'Username should contain a minimum of 6 letters and maximum of 18';
} else {
$confirmeduser = $strippeduser ;
}
if (empty($_POST['password'])){
$errors[] ='Please enter a valid password';
}
if(!preg_match('/^\w{10,40}$/', $_POST['password'])) {
$errors[] = 'Invalid password, use 10 to 40 characters without applying spacing.';
} else{
$password = $_POST['password'];
}
if($_POST['password'] == $_POST['confirm_password']) {
$pass = mysqli_real_escape_string($con, trim($password));
$newpass = password_hash($pass, PASSWORD_DEFAULT) ;
}else{
$errors[] = 'passwords don\'t match.';
}
if(empty($errors)) { // If no problems occurred
//Determine whether the email address has already been registered for a user
$query = mysqli_query($con, "INSERT INTO `customer`(`name`, `email`,
`phone`, `address`, `gender`, `username`, `password`) VALUES($name,$email,$phone,
$address,$gend,$confirmeduser,$newpass)") ;
echo "Done";
// end of mysqli_num_Rows
} // End of if (empty($errors))
else{ // Display the errors if any are found.
echo '
<p class="error">The following error(s) were found in the submitted form :<br>';
foreach ($errors as $msg) { // Echo each error
echo " $msg<br>";
}
}
}
?>
This is the html form
<form action="register.php" method="POST" class="form-horizontal" style="margin-top:30px" id="signup">
<fieldset> <div class="form-group">
<legend> Customer Details </legend>
</div>
<div class="form-group">
<label for="name" class="control-label"> Full Name : </label>
<input type="text" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"
name="name" placeholder="Your Full Name" class="required" title="Please type in your name" >
</div>
<div class="form-group">
<label for="email" class="control-label"> Email address </label>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"
placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="phone" class="control-label"> Phone Number :</label>
<input type="tel" name="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>"
placeholder="08137871320" class="required digits">
</div>
<div class="form-group">
<label for="address" class="control-label"> Contact Address : </label>
<input type="text" name="address" value="<?php if (isset($_POST['address'])) echo $_POST['address']; ?>"
placeholder="No 4,street name,ikeja"
class="required" title="Please type in contact address plus your city's name">
</div>
<!--<div class="form-group">
Drop down menu for selecting a state from the 36 states to be provided
</div>-->
<div class="form-group">
<label for="name">Select Your gender :</label>
<select name="gender" class="form-control">
<option value="male" > Male </option>
<option value="female">Female </option>
</select>
</div>
</fieldset>
<fieldset> <div class="form-group">
<legend> Login Information </legend>
</div>
<div class="form-group">
<label for="username" class="control-label"> Username : </label>
<input type="text" name="username" placeholder="e.g Lords" value="<?php if (isset($_POST['username']))
echo $_POST['username']; ?>">
</div>
<div class="form-group">
<label for="password" class="control-label"> Password : </label>
<input type="password" name="password" id="password" placeholder="Your Password Here">
</div>
<div class="form-group">
<label for="cpassword" class="control-label">Confirm Password : </label>
<input type="password" name="confirm_password" placeholder="Confirm Your Password Here">
</div>
</fieldset>
</div>
</div>
</div>
<div class="form-group" style="text-align:center">
<button type="submit" class="btn btn-success" name="submit"> REGISTER </button>
<button type="reset" id="fat-btn" class="btn btn-danger" data-loading-text="Loading..."> RESET </button> <br>
<p class="lead">
Already a registered user ?,do make use of the
<a href="login.php" class="navbar-link" data-toggle="tooltip" title="When clicked upon,
a page requesting for your username and password is generated,allowing you to book orders">
login page </a>
</p>
</div>
</form>
Thanks a lot for your reply
Since we're more than likely dealing with strings, these variables in your VALUES
($name,$email,$phone,$address,$gend,$confirmeduser,$newpass)
needs to be quoted:
('$name','$email','$phone','$address','$gend','$confirmeduser','$newpass')
Had you checked for errors using or die(mysqli_error($con)) to mysqli_query()
would have signaled the quotes errors.
Sidenote:
You should use prepared statements, or PDO with prepared statements, they're much safer.
Additional note that Barmar spotted:
<?phpinclude 'var.php';
there needs to be a space in there between php and include
<?php include 'var.php';
unless that's a copy/paste error or typo.
and >? again, another spotted error which should be ?>
On the PHP side of things:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
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.