Strange JavaScript, PHP and Google Maps behavior - php

I am breaking my brain in this situation :)
I have a form:
<form method="post" action="">
<input type="hidden" name="entered_markers"
value="<script type='text/javascript'> document.getElementById('rout_markers').value; </script>" />
<input type="submit" value="Enter the trees you saw!" />
</p>
</form>
As you can see, the entered_markers tries to pass some JavaScript variables.
When I process the request, I do this
$chosen_markers = $_POST['entered_markers'];
Then the strange part :)
if ( empty ($chosen_markers) || !isset($chosen_markers) ) {
$errors[] = 'Please click on the map to select spots where you spotted these tree. Markers: '.$chosen_markers;
} else {
// Set something to signify that things are ok
}
And I always have the result that the validation thought the input was not empty, but when I tried to use that variable $rout_markers it just has nothing in it.
Where am I going wrong here? Isn't it sort of a strange thing that is happening? :)

Replace $rout_markers with $chosen_markers

Try it by creating a JavaScript function within your head and pass the form as the parameter to parse it's input fields. I went on and created a dummy text field name "rout_markers" and gave it a value of 300. So, on your PHP side if you look for $_POST['entered_markers'] it would echo out to be 300 if you use the example below:
<html>
<head>
<script type='text/javascript'>
function submitCoor(form){
form['entered_markers'].value = document.getElementById('rout_markers').value;
}
</script>
</head>
<body>
<input type='text' value='300' id='rout_markers' />
<form method="post" action="test.php" onsubmit="submitCoor(this)">
<input type="hidden" name="entered_markers"
value="" />
<input type="submit" value="Enter the trees you saw!" />
</form>
</body>
</html>

Try this:
<form method="post" action="" onsubmit="document.getElementById('entered_markers').value = document.getElementById('rout_markers').value;">
<p>
<input type="hidden" name="entered_markers" id="entered_markers" value="" />
<input type="submit" value="Enter the trees you saw!" />
</p>
</form>
Edit: and replace $rout_markers with $chosen_markers as suggested by webarto.

The code below will probably explain what you could be doing wrong.
$errors = array();
if (
isset($_POST['entered_markers']) // make sure the variable is available
) {
if (
is_string($_POST['entered_markers']) // make sure the data type is string (could be array when form is manipulated)
) {
$markers = trim($_POST['entered_markers']); // trim whitespace and store it in a var
if ($markers !== "") { // if the string is NOT empty
echo "Input given!";
// At this point you could add some more validation to check whether the given input is also what you expect it to be.
// Preform a regexp for lat/lng for example.
echo $markers;
} else {
$errors[] = "Parameter 'entered_markers' is empty.";
}
} else {
$errors[] = "Parameter 'entered_markers' is not a string.";
}
} else {
$errors[] = "Parameter 'entered_markers' is not found.";
}
print_r($errors);

Related

PHP Server Side Form Validation.Empty Form fields are inserted into database

I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}

Why are these <form>'s not recognized by FF and Chrome?

I have the following forms that are rendered by some PHP logic. The forms render fine; you can see the text inputs and submit button and all.
In IE the forms work as expected. The first form goes to 'index.php?subscribe=go' and the second to 'index.php?unsub=go', but in FF and Chrome, clicking the submit button reloads the page (does not go to form action). I have not checked other browsers.
I found in Firebug that the <form> tag doesn't even exist on the page in Firefox. This is very strange; check it out:
else
{
echo '<div class="subs_main">';
if (isset($_GET['subscribe']))
{
if ($_GET['subscribe'] != 'go')
{?>
Subscribe to <b>Bella Blog</b> for specials, sales, news and more!
<br />
<form action="index.php?subscribe=go" method="post" name="subscribe_form" onsubmit="return checkForm();">
Name: <input type="text" name="name" size="15" />
<br />
Email: <input type="email" name="email" size="20" />
<br />
<input type="submit" value="subscribe!" name="submit" />
</form>
<p class="unsub">You can unsubscribe at any time</p>
<?php
}
else
{
// subscribe user
}
}
elseif (isset($_GET['unsub']))
{
if ($_GET['unsub'] != 'go')
{?>
Sorry to see you go! You can re-subscribe at any time!
<br />
<form onsubmit="return checkForm2()" name="unsub_form" method="post" action="index.php?unsub=go">
Email: <input type="email" name="email" size="20" />
<br />
<input type="submit" value="unsubscribe" name="submit" />
</form>
<?php
}
else
{
// process unsubscription HERE
}
}
echo '</div>';
}
This is the JS for form validation (negligible I think because it works in IE and I get the same result when commenting this script out):
<script type="text/javascript" language="javascript">
function checkForm()
{
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
var form = document.forms.subscribe_form;
var name = form.name.value;
var email = form.email.value;
if (name == '' || email == '')
{
alert('You must enter both your name and email address!');
return false;
}
else if (!email.match(regex))
{
alert('You must enter a valid email!');
return false;
}
return true;
}
function checkForm2()
{
var form = document.forms.unsub_form;
var email = form.email.value;
if (email == '')
{
alert('You must enter an email address!');
return false;
}
return true;
}
</script>
If you use POST method into your forms all parameters should be passed through INPUT html elements (i.e. action="index.php?subscribe=go" and action="index.php?unsub=go" are wrong).
The <form> tag doesn't exist? Unless you have code that tailors the output to the USER_AGENT, any browser that passes a given set of GET/POST input to the page should receive identical output. It's possible, of course, that they'll render the page and respond to events in (potentially significantly) different ways, but the source code should be identical.
Post the page source and we can look and see what the issue might be.
This was an outlandish WAMP issue. I had some other PHP code in the file that generated a WAMP error (but no error on the live site) that I've been ignoring because it is meaningless. 'Undefined index' is what it's called and the error appears when you call a PHP variable using $_POST[example] instead of $_POST['example']. Most ridiculous.
So WAMP spit out a bunch of HTML (error <table>s) that got mixed up with the other form on my page. IE can handle the messed up form being there and my form (shown in question) worked normally, while FF/Chrome cannot.
Hope this helps someone.

php form validation issues - cannot print to header

I have a php form that saves the info to my database and sends an email upon completion. however it will not validate the fields to see if they are null, instead it prints both the set and not set options. Any ideas as to why this could be happening? It worked perfectly before i added the form field validation to it.
As a side note it works in FF and Chrome due to the html 5 aria-required, but not in IE
html
<form id="contact" name="contact" action="register1.php" method="post">
<label for='Cname'>Camper Name</label>
<input type="text" name="Cname" maxlength="50" value="" required aria-required=true />
<input type="hidden" id="action" name="action" value="submitform" />
<input type="submit" id="submit" name="submit" value="Continue to Camp Selction"/>
</form>
php
<?php
//include the connection file
require_once('connection.php');
//save the data on the DB and send the email
if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
//recieve the variables
$Cname = $_POST['Cname'];
//form validation (this is where it all breaks)
if (isset($Cname)) {
echo "This var is set so I will print.";
}
else {
echo '<script type="text/javascript">alert("please enter the required fields");</script>';
}
//save the data on the DB (this part works fine)
<?php
$Cname = isset($_POST['Cname']) ? $_POST['Cname'] : null;
if (isset($Cname)) {
echo "This var is set so I will print.";
}
// OR
if (isset($_POST['Cname'])) {
// Perform your database action here...
}
?>
Consider using PHP's empty function
PHP.Net Manual Empty()
You can update your code to the following:
if(!empty($Cname)) {
echo "This var is set so I will print.";
}
Do you just need an "exit()" in the else?

PHP Show error messages in order and re-display correct fields

I have an email form that checks three fields, name, valid email and comments. But the way it's set up now, since name and comments are in one function it first checks name and comments even if email is not valid, how can I re-write it so it checks the fields in order. Also, I would like to re-display the fields that have no errors, so the user doesn't have to type again. Please help. Thanks
<?php
$myemail = "comments#myemail.com";
$yourname = check_input($_POST['yourname'], "Enter your name!");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$subject = check_input($_POST['subject']);
$comments = check_input($_POST['comments'], "Write your comments!");
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Enter a valid E-mail address!");
}
exit();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!doctype html>
<html>
<body>
<form action="myform.php" method="post">
<p style="color: red;"><b>Please correct the following error:</b><br />
<?php echo $myError; ?></p>
<p>Name: <input type="text" name="yourname" /></P>
<P>Email: <input type="text" name="email" /></p>
<P>Phone: <input type="text" name="phone" /></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
exit();
}
?>
First off, I would suggest you validate ALL of the fields at once, and display all appropriate error messages on the form. The primary reason is that it can be bad user experience if they have to submit your form a whole bunch of times because they have to address one error at a time. I'd rather correct my email address, password, comments, and selection in one try instead of fixing one at a time just to reveal what the next error is.
That said, here are some pointers on validating the form like you want. This is typically how I approach a form doing what you want to do. This assumes your form HTML and form processor (PHP) are together in the same file (which is what you have now). You can split the two, but the methods for doing that can be a bit different.
Have one function or code block that outputs the form and is aware of your error messages and has access to the previous form input (if any). Typically, this can be left outside of a function and can be the last block of code in your PHP script.
Set up an array for error messages (e.g. $errors = array()). When this array is empty, you know there were no errors with the submission
Check to see if the form was submitted near the top of your script before the form is output.
If the form was submitted, validate each field one at a time, if a field contained an error, add the error message to the $errors array (e.g. $errors['password'] = 'Passwords must be at least 8 characters long';)
To re-populate the form inputs with the previous values, you have to store the entered values somewhere (you can either just use the $_POST array, or sanitize and assign the $_POST values to individual variables or an array.
Once all the processing is done, you can check for any errors to decide whether the form can be processed at this point, or needs new input from the user.
To do this, I typically do something like if (sizeof($errors) > 0) { // show messages } else { // process form }
If you are re-displaying the form, you simply need to add a value="" attribute to each form element and echo the value that was submitted by the user. It is very important to escape the output using htmlspecialchars() or similar functions
With those things in place, here is some re-work of your form to do that:
<?php
$myemail = "comments#myemail.com";
$errors = array();
$values = array();
$errmsg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST as $key => $value) {
$values[$key] = trim(stripslashes($value)); // basic input filter
}
if (check_input($values['yourname']) == false) {
$errors['yourname'] = 'Enter your name!';
}
if (check_input($values['email']) == false) {
$errors['email'] = 'Please enter your email address.';
} else if (!preg_match('/([\w\-]+\#[\w\-]+\.[\w\-]+)/', $values['email'])) {
$errors['email'] = 'Invalid email address format.';
}
if (check_input($values['comments']) == false) {
$errors['comments'] = 'Write your comments!';
}
if (sizeof($errors) == 0) {
// you can process your for here and redirect or show a success message
$values = array(); // empty values array
echo "Form was OK! Good to process...<br />";
} else {
// one or more errors
foreach($errors as $error) {
$errmsg .= $error . '<br />';
}
}
}
function check_input($input) {
if (strlen($input) == 0) {
return false;
} else {
// TODO: other checks?
return true;
}
}
?>
<!doctype html>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<?php if ($errmsg != ''): ?>
<p style="color: red;"><b>Please correct the following errors:</b><br />
<?php echo $errmsg; ?>
</p>
<?php endif; ?>
<p>Name: <input type="text" name="yourname" value="<?php echo htmlspecialchars(#$values['yourname']) ?>" /></P>
<P>Email: <input type="text" name="email" value="<?php echo htmlspecialchars(#$values['email']) ?>" /></p>
<P>Phone: <input type="text" name="phone" value="<?php echo htmlspecialchars(#$values['phone']) ?>"/></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" value="<?php echo htmlspecialchars(#$values['subject']) ?>" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"><?php echo htmlspecialchars(#$values['comments']) ?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
I have a more advanced example which you can see here that may give you some guidance as well.
Hope that helps.
The simplest option is to use a form validation library. PHP's filter extension, for example, offers validation and sanitization for some types, though it's not a complete solution.
If you insist on implementing it yourself, one issue you'll have to consider is what counts as the order: the order of the elements in the form or the order of the user input in $_POST. On most browsers, these should be the same, but there's no standard that enforces this. If you want to go off of form order, you'll need to define the form structure in one place, and use that information to do things like generating or validating the form (a consequence of the Don't Repeat Yourself (DRY) principle). Iterating over the appropriate structure will give you the order you desire: looping over the form gives you form order, whereas looping over $_POST gives you user input order.
It looks like you want to more than simply validate the data; you also want to prepare it for use, a process called "sanitization".
When it comes to sanitization, define different kinds of sanitizers, rather than a single check_input function. Specific sanitizers could be functions, or objects with an __invoke method. Create a map of form fields to sanitizers (for example, an array of input name to sanitizer callbacks). The order of the elements in the mapping sets the order of the sanitization; if you use a single structure to define the form information, the display order and sanitization order will thus be the same.
Here's a very broad outline:
# $fields could be form structure or user input
foreach ($fields as $name => $data) {
# sanitize dispatches to the appropriate sanitizer for the given field name
$form->sanitize($name, $data);
# or:
//sanitize($name, $data);
# or however you choose to structure your sanitization dispatch mechanism
}
As for setting an input's value to the user-supplied data, simply output the element value when outputting the element. As with all user input (really, all formatted output), properly escape the data when outputting it. For HTML attributes, this means using (e.g.) htmlspecialchars. Note you should only escape outgoing data. This means your sanitization functions shouldn't call htmlspecialchars.
You can improve usability by placing each error next to the corresponding input, adding an "error" class to the element and styling the "error" class to make it stand out. Improve accessibility by wrapping <label> elements around the label text.
Use this structure of script:
<?php
$errors = array();
if (isset($_POST['send'])) {
// check data validity
if (!mailValid($_POST['email']))
$errors[] = 'Mail is not valid';
...
// send data by email
if (!$errors) {
// send mail and redirect
}
}
?>
<html>
...
<?php
if ($errors) {
// display errors
foreach ($errors as $error) {
echo "$error<br />";
}
}
?>
<form ...>
...
Email: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>" />
...
</form>
...
</html>
You could always do it like this, using filter_var and in_array checks:
<?php
$myemail = "comments#myemail.com";
//Pre made errors array
$errors=array('name'=>'Enter Your name',
'email'=>'Please enter valid email',
'phone'=>'Please enter valid phone number',
'subject'=>'Please enter valid subject, more then 10 chars',
'comment'=>'Please enter valid comment, more then 10 chars');
//Allowed post params and its validation type
$types = array('name'=>'string',
'email'=>'email',
'phone'=>'phone',
'subject'=>'string',
'comment'=>'string');
//A simple validation function using filter_var
function validate($value,$type){
switch ($type){
case "email":
return ((filter_var($value, FILTER_VALIDATE_EMAIL))?true:false);
break;
case "phone":
return ((preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $value))?true:false);
break;
case "string":
return ((strlen($value) >=10 )?true:false);
break;
default:
return false;
break;
}
}
//If forms been posted
if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
//Assign true, if all is good then this will still be true
$cont=true;
$error=array();
foreach($_POST as $key=>$value){
//if key is in $types array
if(in_array($key,$types)){
//If validation true
if(validate($value, $types[$key])==true){
$$key=filter_var($value, FILTER_SANITIZE_STRING);
}else{
//Validation failed assign error and swithc cont to false
$error[$key]=$errors[$key];
$cont=false;
}
}
}
}
if($cont==true && empty($error)){
//Send mail / do insert ect
}else{
//Default to form
?>
<!doctype html>
<html>
<body>
<form action="" method="post">
<p>Name: <input type="text" name="name" value="<?=#htmlentities($name);?>"/> <?=#$error['name'];?></P>
<P>Email: <input type="text" name="email" value="<?=#htmlentities($email);?>" /> <?=#$error['email'];?></p>
<P>Phone: <input type="text" name="phone" value="<?=#htmlentities($phone);?>"/> <?=#$error['phone'];?></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /> <?=#$error['subject'];?></p>
<p>Comments: <?=#$error['comment'];?><br />
<textarea name="comment" rows="10" cols="50" style="width: 100%;"><?=#htmlentities($comment);?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
}?>

Where would I run this validateForm method? I'm a very newbie PHP developer getting the hang of web developing

Here's what I have:
<html>
<head>
<?php
$validForm = false;
function getValue($field){
if(isset($_GET[$field])){
return $_GET[$field];
}
else{
return "";
}
}
function validateForm(){
//magic goes here.
}
?>
</head>
<body>
<?php if($validForm == false){ ?>
<form action="class2.php" method="get">
<dl>
<dt>First Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('name')) ?>" name="name" />
</dd>
<dt>Last Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('lastname')) ?>" name="lastname" />
</dd>
<br />
<dt>
<input type="submit" value="enviar" />
</dt>
</dl>
</form>
<?php
} else {
?>
<h1>Congratulations, you succesfully filled out the form!</h1>
<?php }
?>
</body>
Where would I put the validateForm() call? I'm not sure.
What I want is to continue showing the form until the $validForm variable is true. :)
Thank you SO you always help me out.
function validateForm(){
if ( ) // Your form conditions go here
{
return true;
} else {
return false;
}
}
if ( $_GET ) // Only validate the form if it was submitted
{
$validForm = validateForm();
} else {
$validForm = false;
}
Examples for some conditions:
if ( !empty ( $_GET[ 'name' ] ) and !empty ( $_GET[ 'lastname' ] ) ) // Check if the user entered something in both fields
I can only recommend you to change your getValue function too.
It would be a good idea to change
return $_GET[$field];
to something like
return htmlspecialchars ( trim ( $_GET[$field] ) );
This will remove unnecessary whitespace and escape the output at once.
The next or probably first step you should take would be to change your form from GET to POST as it is, in most cases, a bad idea to send form data via GET.
You have to add a name to your submit button :
<input type="submit" value="enviar" name="validate" />
And after the declaration of validateForm
you put
if(getValue("validate") != "")
validateForm();
I'd check for the $_POST-variables in your getValue-function as you're trying to validate form-data (your checking $_GET-variables which is data submitted through the URL), you also may want to add "trim"
give the submit-button an id and check if the form has beed submitted that way
e.g. <input type="submit" value="enviar" id="submitButton" />
setting $validForm would look this this: $validForm = validateForm(); (instead of "$validForm = false;")
your validateForm-function should then check whether "$_POST["submitButton"]" is set and if your data is valid (set, right type, etc. etc.), if all of that is ok, return "true", otherwise "false"
<html>
<head>
<?php
$validForm = validateForm();
C.

Categories