Basic Form Validation Check Number? - php

In this script I am checking if fields are not empty and email address is syntactically correct. How to add a text input at the bottom of my form for a basic sum question, e.g. (2+5)= I want to add a validation element to my current script to check if this equals 7.
if (empty($name) || empty($phone) || empty($email) || empty($enquiry))
{
echo " * Sorry all fields are required.";
}
elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email))
{
print "<p>Sorry the email address you entered looks like it's invalid.</p>";
}
else
{
mail($to, $sub, $mes, $headers);
print "<p>Thank you ".$name." for contacting us.<br /><br />We will be in touch shortly.</p>";
}

If you are just wanting to validate a static sum, e.g. you know it is always going to be ( 2 + 5 ) = 7
Then you could just write a simple function to check the posted value.
// this being your posted value;
$validate = 7;
function SumCheck($value){
if ( 2 + 5 == $value ){
return true;
}
else{
return false;
}
}
Then change your initial line to;
if (empty($name) || empty($phone) || empty($email) || empty($enquiry) || !SumCheck($validate))
However, I would suggest using RECAPTCHA as Robert Podwika has suggested.

1 If your session is not started use in the very first line
session_start();
2 Before form is shown. Add this code. Also remember that session start must be also in file where validation is.
$numa = rand(1,5);
$numb = rand(0,4);
$_SESSION['valid_res'] = $numa+$numb;
echo "<p>To submit form please solve this equatation $numa + $numb = ?";
echo '<input type="text name="result_val" />';
3 In validation functions you should check
if(intval($_POST['resul_val']) != $_SESSION['valid_res'])
{
echo "sorry you put wrong result in validation form";
}
However, if I were you I'd use RECAPTCHA

Related

Form submission results in a blank page in PHP

I am trying to make a login system and i want to create a conditional statement that checks whether the global variable $_POST['submit-form'] is set.
If the global variable $_POST['submit-form'] is set then i want to echo out the fields of the submitted forms. This works fine..
The problem comes when i want to check whether the global variable $_POST['submit-form'] is empty, i get a blank page when i submit the form with nothing. It is supposed to echo out something like "You have entered nothing, please try again'.
I don't know what is wrong.
This is the code for the form.
<form action="test-form2.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" name="submit-form" value="submit">
</form>
..and this is the code for the form handler.
<?php
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
// header('refresh=3;url = /test-form1.php');
}
?>
Your $_POST always have submit-form (and it's always not empty), so if statement always returns true. Try to check (for example) only that $_POST['name'] and $_POST['email'] are not empty.
The problem with your code is that checking if it's set isn't enough .. Because it may be set and be empty -- Realistically what you want is to check both isset and whether it's empty IE:
if (isset($_POST['submit-form'] && $_POST['submit-form'] != '' && $_POST['submit-form'] != null)
If the above if statement fails your value for $_POST['submit-form'] is most likely not being submitted.
UPDATE
Check for blank fields
if ($_POST['name'] != '' && $_POST['email'] != ''){
// Do stuff
}else{
if ($_POST['name'] == ''){
echo "name is empty";
}
if ($_POST['email'] == ''){
echo "email is empty";
}
}
That's because isset($_POST['submit-form']) returns true even if you don't input anything in Name and E-mail fields, it's value would be submit string when hit submit button to submit the form. This is the reason else part of below block is not getting executed.
if(isset($_POST['submit-form'])) {
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
Use var_dump($_POST); to see the complete array structure. having said these, you can use the following snippet to achieve the desired result,
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}else{
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
}
Validation and scrutinization of user inputs should be your next action items in the list.

How can I give an error if all fields are not filled in?

Basically this is my registration form. I want to make it so if all the fields are not filled in it will give an error. What do I do from here? I would also like to display the error as $msg
<?php
include'db.php';
$msg='';
if (empty($_POST[''])
|| empty($_POST['password'])
|| empty($_POST['repassword'])
|| empty($_POST['user_firstname'])
|| empty($_POST['user_lastname'])
){
// details sent Form
$company=mysql_real_escape_string($_POST['company']);
$address=mysql_real_escape_string($_POST['address']);
$email=mysql_real_escape_string($_POST['email']);
$phone=mysql_real_escape_string($_POST['phone']);
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/'; //this defines what a valid email should be
if(preg_match($regex, $email))
{
$activation=md5($email.time()); // Encrypted email+timestamp, so randomly generated and unique
$count=mysql_query("SELECT uid FROM preciousmetals WHERE email='$email'") or die(mysql_error());
if(mysql_num_rows($count) < 1)
{
mysql_query("INSERT INTO preciousmetals(company,address,email,phone,activation) VALUES('$company','$address','$email','$phone','$activation');");
// sending email
include 'smtp/Send_Mail.php';
$to=$email;
$subject="Email verification";
$body='Hello, we need to make sure you are human. Please verify your email and get started using your Website account. '.$base_url.''.$activation.'';
Mail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= '<font color="#cc0000">This email is already in use, please enter a different one.</font>';
}
}
else
{
$msg = '<font color="#cc0000">The email you have entered is invalid, please try again. </font>';
}
}
?>
Thank you for helping out!
Simply do
if (empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])){
$msg = 'You have not filled all fiels';
} else {
// details sent Form
......
}
echo $msg;
And also check for filter_var() for email validation its much more nicer than regEx
http://php.net/manual/en/filter.examples.validation.php

PHP form validation that includes SUBMIT button

I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.

Form validation - security

So I'm working on a register form and I have four fields: name, username, email and password. I pick up the values of these fields in jQuery and depending on if all the fields are filled, I pass them onto a PHP script via ajax. Is that safe for form validations? I was worried about data getting manipulated by the user.
Further on in the php script, I check if all the posted values have data in them, only then will I proceed onto doing some validations... The validations are the parts where I'm worried that it's not the best and there are many flaws with it.
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if (!preg_match("/^[A-Za-z '-]+$/i", $name)) {
$errors = "Please enter a valid name.";
} else if (!preg_match("/^[A-Za-z]+\s[A-Za-z]+$/", $name)) {
$errors = "Please enter your first and last name.";
} else if (strlen($username) <= 3 || strlen($username) > 15) {
$errors = "Please pick a username between 4 - 15 characters. Be creative.";
} else if (!preg_match("/^[A-Za-z][A-Za-z0-9_.-]{4,15}$/", $username)) {
$errors = "Please pick an alphanumeric username between 4 - 15 characters.";
} else if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors = "Please enter a valid email.";
} else if (strlen($username )< 6 || strlen($username) > 32) {
$errors = "Your password must atleast be 6 characters.";
} else {
echo "valid";
}
Are these validation steps secure? Are there any loop holes that the user can manipulate the data? Also, I was hoping for the full name input, the user would input the first AND the last name. Are these good enough?
Thank you.
As you asked for review, pls read what you wrote here...
} else if (strlen($username )< 6 || strlen($username) > 32) {
$errors = "Your password must atleast be 6 characters."
Some times java script might not be the best solution since some users disables it. So consider that too.
And when inserting data to databases we should consider about 'sql injection', 'encryption methods' etc..
I Think you should read and study some more articles on the internet. Try these links.
http://www.sitepoint.com/form-validation-with-php/
http://www.w3resource.com/javascript/form/javascript-sample-registration-form-validation.php
http://www.hscripts.com/scripts/JavaScript/form-validation.php
I use this
$var = filter_var($_POST['xxx'], FILTER_SANITIZE_STRING);
If (preg_match('/^([a-zA-Z]){4,15}$/', $var)){ // must character lower or upper, minimal 4 and max 15 characters
$con1 = true;
} else{
$con2 = false;
}
// $cond2
// $cond3
// $cond4
// CHECK ALL CONDITION BEFORE INSERT
If (($cond1 && $cond2 && $cond3 && $cond4) == true){
(with prepared statement)
$sql = Insert into;
} else{
Header("Location: "); // if you redirect user to another page
And echo the errors with ajax
}
Hope you can consider this

php isset() is_string() not working

I have a rough php script that sees if a user has filled in the html form input after they have clicked submit. I am having a problem with getting isset() and is_string() to work. If I use isset() the form is emailed even if the form inputs are left blank, is_string() throws an error messages even if the form input are filled in. I have tried !isset() and that still sends blank input. The only thing working is if I use == NULL. At this moment in time I am not going to validate the input as I am trying to understand why this isn't working as I am pretty new to PHP.
$subject = "Feedback from Your Website.";
$email = ($_POST['email']);
$name = ($_POST['name']);
$message = ($_POST['feedback']);
if (isset($_POST["name"]))
{
//send message
mail($subject, $name, $email, $message);
}
else
{
//error message
echo "Please do not miss out any fields";
}
I also tried:
if (isset($_POST["name"], $_POST['email']))
{ }
if (isset($name, $email))
{ }
if (is_string($name || $email))
{ }
But all failed, so far all that's working is:
if ($name == NULL || $email == NULL || $message == NULL)
{ }
Thank you in advance.
Try to use empty(). This function return TRUE if a variabile is empty or non set, FALSE otherwise.
if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["feedback"]))
{
//error message
echo "Please do not miss out any fields";
}
else
{
//send message
mail($subject, $name, $email, $message);
}
is_string($name || $email) is not working because $name || $email is cast to a boolean and a boolean is not a string.
isset() function will return a True value after your form submitting. Actually, your field has been sent to your target file. So your code will send emmial. For what you need, you must use the code below:
if (isset($_POST["name"]) && $_POST["name"] != '') {
// do something
}
isset checks if value is created in the array. It IS going to be there always as the form always have the same fields, empty or not. You need to check their content
isset() returns true because $_POST['email'] has been set. It simply is empty. Since you submit the form all the variables of the form have been set.
You have to write this
if (isset($_POST["email"]) && $_POST["email"] != '')
How about empty( ) you can check the details of the function in te php manual .

Categories