I have this simple php code that generate a random code and display it to the user. I need to verify using a text input if the user insert the displayed code, like a captcha, but i will use this script to redirect the user after the verification,to the registration form page. The code is generated, but i can't verify it, maybe i've missed something in the code?
NB: This is not a spam prevention system. As said in the comments, there are valid solution better than this to prevent spam. This is a starting draft for an user invitation system, if you want to downvote the question please consider this.
<?php
function randomCode() {
$code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime() * 1000000);
$i = 0;
$rand_Code = '';
while ($i <= 7)
{
$num = rand() % 33;
$tmp = substr($code_variable, $num, 1);
$rand_Code = $rand_Code . $tmp;
$i++;
}
return $rand_Code;
}
$code = randomCode();
if(isset ($_POST['verify'])){
if($_POST['user_code'] == $code ){
echo 'Valid code.';
header('Location: index.php');
}
}
?>
<form method="post" action="">
<input type="text" name="verification_code" disabled value="<? echo $code;?>">
<input type="text" name="user_code">
<button type="submit" name="verify">Verify code</button>
</form>
You will never get Valid code. being displayed on the screen since every time user clicks on Verify code button, the page will refresh and a new random captcha code will get generated and stored in $code. So that's why $_POST['user_code'] will never be equal to $code.
One workaround would be to append the captcha code in the URL itself, so that you could verify the authenticity of user-inputted captcha by comparing it with $_GET[...] data. So you need to change your form in the following way,
<form method="post" action="?captcha=<?php echo $code; ?>">
<input type="text" name="verification_code" disabled value="<?php echo $code;?>">
<input type="text" name="user_code">
<button type="submit" name="verify">Verify code</button>
</form>
Subsequently, verify captcha in the following way,
// your code
if(isset ($_POST['verify'])){
if($_POST['user_code'] == $_GET['captcha'] ){
// your code
}
}
Sidenote(s):
Don't output anything before the header(...); statement, otherwise you would see headers already sent error. Go through this SO thread to get more info on this.
header(...); alone is not sufficient to redirect the user to a different page, use exit(); after header(...); statement.
I've added the php mail() function to send the invitation code to users. It's working fine, i've divided the code into two parts. the first one manage the user invitation code sending:
<form method="post" action="?invitation=<?php echo $code; ?>">
<label for="email">Email</label>
<input type="text" name="email">
<button type="submit" name="send_invitation">Send invitation code</button>
</form>
<?php
session_start();
ob_start();
if(isset($_POST['send_invitation'])){
function randomCode()
{
$code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime() * 1000000);
$i = 0;
$rand_Code = '';
while ($i <= 7)
{
$num = rand() % 33;
$tmp = substr($code_variable, $num, 1);
$rand_Code = $rand_Code . $tmp;
$i++;
}
return $rand_Code;
}
$_SESSION['code'] = randomCode();
$_SESSION['tmp_mail'] = $_POST['email'];
if(isset($_POST['verify'])){
$to = $_POST['email']; // this is your Email address
$from = "noreply#domain.com"; // this is the sender's Email address
$subject = "Affiliate invitation code";
$message = $_SESSION['code'] . " " . " is your invitation code.";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
?>
The second part of the script is on another page and manage the check for the code matching between stored code into the $_SESSION['code'] variable and the user input
<?php
session_start();
ob_start();
function redirect(){
header('refresh:3; url=affiliate/index.php');
exit;
}
if(isset($_POST['verify'])){
if($_POST['user_code'] == $_SESSION['code']){
echo "Valid invitation code. You can now register using $_SESSION['tmp_mail'] email address.";
} else { echo "Wrong code. Please enter a valid code or request a new one."; }
?>
<form method="post" action="?invitation=<?php echo $code; ?>">
<label for="Code">Invitation Code</label>
<input type="text" name="user_code">
<button type="submit" name="verify">Send invitation code</button>
</form>
Related
I'm working on password reset in core php.
I'm sending code variable from reset.php to resetPassword.php page like this:
reset.php
$code = uniqid(true);
$url = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/resetPassword.php?code=$code"
resetPassword.php
global $code;
if(!isset($_GET['code'])){
echo "There is No Code there !!!";
}
if(isset($_GET['code'])){
$code = $_GET['code'];
echo "The code is set at first , just at visit of the page ".$code;
}
// make sure there is row in the table that matches that passed code
$findEmail = mysqli_query($link,"SELECT `email` from resetpasswords WHERE `code` = '$code' ");
if(mysqli_num_rows($findEmail)==0){ // if no row found
echo "<h2 class = 'text text-center'>No Record regarding this email !</h2>";
exit();
}
// when form submits
if(isset($_POST['reset'])){
$password = md5($_POST['password']);
$confirm = md5($_POST['confirm']);
if($password!=$confirm){
echo "Password Don't matches !";
exit();
}
$row = mysqli_fetch_array($findEmail);
$email = $_POST['email'];
$updatePass = mysqli_query($link,"UPDATE `user` SET user_password = '$confirm' where email = '$email'");
if($updatePass){
$query = mysqli_query($link,"DELETE FROM resetpasswords where code = '$code' ");
exit('Password Updated, Please Login with the New Password');
}
else{
exit('Something went wrong');
}
}
On the same page resetPassword.php, I have the following code:
<form action="resetPassword.php" method="POST">
<div class="form-group">
<label for="password2">Password:</label>
<input type="password" class="form-control" name="password" id="password2" onkeyup="checkPass();">
</div>
<div class="form-group">
<label for="confirm2">Confirm Password:</label>
<input type="password" class="form-control" name="confirm" id="confirm2" onkeyup="checkPass();">
<span id="confirm-message2" class="confirm-message"></span>
</div>
<input type="hidden" value="<?php echo $code;?>">
<input type="submit" name="reset" value="Update Password" class="btn btn-success">
</form>
Problem:
The problem is when I submit the form , it goes all the way to the top of the page, and start executing the resetPassword.php page from the top, due to which for resetPassowrd.php page, it can't get that $code variable.
Because when I submit the form,the condition (!isset($_GET['code'])) at top of resetPassword.php becomes true and it gives me:
There is No Code there !!!
And I want to have that $code when I submit the form.
What I tried:
I tried to use hidden field with value of $code but that didn't worked.
please help me thanks
Consider the below points
1) Use prepared statements and parameterized queries.
2) Use password_hash() and password_verify() to secure your password.
3) In resetPassword.php page, if you submit the form with action="resetPassword.php" this will redirect to resetPassword.php. So replace your action with this
$full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
<form action="<?php echo $full_url ?>" method="POST">
You are missing name attribute in your hidden field and hence you are not able to find the value of $code.
Instead of
<input type="hidden" value="<?php echo $code;?>">
Try
<input type="hidden" value="<?php echo $code;?>" name="code" />
Thanks in advance for your help. I am new to PHP. I have done a lot of learning to get to this point, but I am currently stuck.
I have a form with a 'fields-section' and a 'proof-section' that has 3 buttons - proof, edit and send. Initially, the 'fields-section' is displayed and the 'proof-section' is hidden. Of the 3 buttons, the 'proof' button is visible while the other 2 are not. After the form is completed and 'proof' is clicked, the fields are validated, some fields are transformed into Hebrew and a proof is presented to the user by hiding the 'fields-section' and showing the 'proof-section'. Here the 'edit' and 'send' buttons are available and the 'proof' button is hidden. I am integrating this form within a Wordpress page template.
I am finding that the PHP variables do not have any value and I don't understand why.
If I change echo htmlspecialchars($line1); to
if(isset($_POST['line1'])){
echo htmlspecialchars($_POST['line1']);
}
It works...but this solution doesn't work for $line1_hebrew because this is a calculated field. I deleted unnecessary code below to keep it short.
Below is my code from the Wordpress template:
<?php
include "hebrew-memorial-creator.php";
add_action( 'genesis_after_loop', 'em_form');
/**
* Output the form to the page
*
*/
function em_form() {
?>
<div id="hebrew-memorial-creator">
<form name="hebrewMemorialForm" action="" method="POST">
<div id="field_section">
<div>
<label for="line1">Line 1: </label><input type="text" name="line1" id="line1" value="<? echo htmlspecialchars($line1);?>" size="50" maxlength=40 />
<input type="hidden" name="line1_hebrew" id="line1_hebrew" value="<?php htmlspecialchars($line1_hebrew);?>" />
</div>
.... deleted some fields here
</div><!--field-section-->
<input type="submit" id="proof_button" name= "proof_button" value="PROOF">
<input type="submit" id="edit_button" name="edit_button" value="EDIT">
<input type="submit" id="submit_button" name="submit_button" value="SEND">
<div id="proof_section">
<?php echo htmlspecialchars($proof);?>
</div><!--proof-section-->
</form>
</div><!--hebrew-memorial-creator-->
<?php
} // end function em_form
genesis();
?>
Below is my code from hebrew-memorial-creator.php:
<?php
if (isset($_POST['line1'])) { $line1 = $_POST['line1']; }
... deleted code for other fields...
if(isset($_POST['proof_button'])) {
$formerrors = false;
// validate fields
// email address is required
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'email error';
$emailErr = 'Please enter a valid email address';
$formerrors = true;
}
if (! ($formerrors)) {
// for line1 - line4, create line1_hebrew - line4_hebrew - converting lowercase letters to Hebrew characters
// and write to hidden form fields
$line1_hebrew = convert($line1);
... deleted code for additional fields
// all fields validated
// show proof fields and submit/proof buttons
$proof = '<div class="bronze"><p style="font-size: 36px; text-align:center;">HERE IS YOUR PROOF :</p>';
$proof .= '<p>Line1: ' . htmlspecialchars($line1) . ' ==> ' . htmlspecialchars($line1_hebrew) . '</p>';
... deleted code for other fields
$proof .= '</div>';
$proof .= "<script>
$('#field_section').hide();
$('#proof_section').show();
$('#proof_button').hide();
$('#edit_button').show();
$('#submit_button').show();
$('html,body').scrollTop(0);
</script>";
` // curious if anyone has a better solution to hiding/showing field`
} // end if no errors
return;
} // end proof button pressed
if (isset($_POST['submit_button'])) {
....deleted formatting of mail variables
mail( $to, $subject, $message, $headers );
wp_redirect( get_site_url() . '/thank-you');
} // end send button pressed
// replacing any lowercase characters with their hebrew character equivalent
function convert($line) {
if (($line == '') || ($line == ' ')) {
return $line;
}
$newLine = "";
for ($i=0; $i < strlen($line); $i++) {
//$character = substr($line, $i, 1);
$character = $line[$i];
... deleted code
} // end for
return $newLine;
} // end function convert
?>
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.
In my website, it presents a list of program titles. When a title is clicked, it displays the content and an email form. The form just takes an email and mails the title as the subject and the content of the page in the email.
The link will pass a variable 'info'. 'info' contains the ID for the post in my database. The problem occurs when I click the submit button. It will not send an email, and refresh the page. This causes the url to loose the 'info' variable and loose all content on the page.
The page works perfectly if I hardcode the ID in the php and don't use $_GET['info'].
Is there something I am missing?
<?php
$id = $_GET['info'];
/*****************************************************
open conection to the mySQL database
******************************************************/
$configs = include('config.php');
//Create a connection
$con = mysqli_connect(
$configs['host'], //host
$configs['username'], //username
$configs['password'], //password
$configs['dbname'] //dbname
);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
/*****************************************************
Populate the page
******************************************************/
$sql="
SELECT p.post_title, p.post_content
FROM they_posts AS p
WHERE p.ID='".$id."'
";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
/*Title*/
echo '<h1>'.$row['post_title'].'</h1><hr>';
/*content*/
echo '<h2>Details: </h2><br>'.$row['post_content'].'<br>';
$title= $row['post_title'];
$content = $row['post_content'];
/*****************************************************
E-mail Form
******************************************************/
include('includes/email_test.php');
}
?>
And this is the email_test.php
<div data-role="collapsible">
<h1>Send Reminder Email</h1>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
}
else // the user has submitted the form
{
// Check if the "from" input field is filled out
if (isset($_POST["to"]))
{
// Check if "from" email address is valid
$receivecheck = spamcheck($_POST["to"]);
if ($receivecheck==FALSE)
{
echo "Invalid input";
}
else
{
$to = $_POST["to"]; //receiver
$subject = $title;
$message = $content;
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("$to",$subject,$message,"From: noreply#address.com\n");
echo "reminder has been sent";
}
}
}
?>
</div>
I have used isset($id) to display a back button for when submit is pressed. This will bring back the information but the email is still never sent.
In your scenario you must have info=post_id in your current url to get $_GET['info']
1st way:
Change your form action like this:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"].'?info='.$_GET['info']; ?>">
then in action it will be :
/your_page.php?info=current_post_id
then in action page you can get info by $_GET['info']
2nd way:
or you can add extra hidden form field in your form for post_id like this:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
<input type="submit" name="submit" value="Submit Feedback">
<input type="hidden" name="post_id" value="<?php echo $_GET['info'];">
</form>
After that In your action page you can get post_id by $_POST['post_id']
It should make sense!
Thanks
$_GET['info'] will only work if your form is defined with method='GET'.
If your form is defined with method='POST' then you need to use $_POST['info'].
If you want your code to work no matter whether the form is using GET or POST, then use $_REQUEST['info'].
I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.