PHP Form Validation PowerPoint

advertisement
Stupid Browser Tricks with PHP and JavaScript
By Chris Winikka

Isn’t JavaScript Validation Enough?
 Some people turn off JavaScript
 Some people have bad intentions

PHP is the only way to ensure that the information from a form is…
 not empty
 in the correct format
 not filled with nasty, evil code
▪ with sharp pointy teeth

Why even use JavaScript?
 convenience
▪ the user finds out something is missing before sending it off (before leaving the form
page)
▪ it might catch a mistake in an email address
 less processor time
▪ If the php file catches an error, it has two main options:
▪ It has to send the user back to the form page, or
▪ It gives a warning and forces the user to use the back button
▪ If you catch problems with JavaScript before running the processor, the php file may only
have to be run once

PHP, like all high-level computer languages has functions
 built-in functions
▪ these are handy functions that the makers of php thought you might
find useful
 user-defined functions
▪ you get to create your own

What is a function?
 function is reusable code
 if there’s anything you want to do more than one time, you
should write a function for it

You already used the date() function
 you provided some codes
 the function used those codes to format the date and time


According to OWASP.org, there are 10 main security flaws
The top 2 flaws to prepare for are:
Cross-site Scripting Flaws (XSS):
1.
▪
▪
Injection Flaws:
2.
▪
▪
Injection occurs when user-supplied data is sent to an interpreter as part of a
command or query.
The attacker's hostile data tricks the interpreter into executing unintended
commands or changing data.
There are other flaws to be concerned with, but we won’t cover those
because…





occur whenever an application takes user supplied data and sends it to a web browser
without first validating or encoding that content.
XSS allows attackers to execute script in the victim's browser which can hijack user
sessions, deface web sites, possibly introduce worms, etc.
We are not learning how to do passwords & password encryption
We are not learning how to do file uploads
For the most part our simple applications are not big targets
For more information on security, visit the Open Web Application
Security Project (OWASP) website




Validate
Validate
Validate
Make sure the data
 Is in the correct format
▪ A number is an integer
▪ A name is in the form of a string
▪ An email is in the format of an email
 Is not empty
 Does not have any code you don’t want it to have




The first step in validation is making sure
variables aren’t empty
Unfortunately, a field filled with spaces is not
technically empty
That’s why you need the trim() function
How it works:
 Pass it a variable and
 It removes white spaces before or after a field entry
(in the variable)
 Do it like so…
 $name = trim($name);

empty() – checks to see if a variable is empty or not
 Pass it a variable
 If the variable has no value (it’s empty), it returns True
▪ “Yes, it is empty”
 If the variable does have a value (not empty), it returns False
▪ “No, it’s not empty”

The empty() function in its natural habitat
 Typically, you use the empty() function to check to see if it is not empty
▪ For this, you use the special NOT code, “!”
▪ Place the exclamation mark (NOT) in front of the function
 Example:
▪ if (!empty($variable)) {
echo ‘<p>It’s not empty</p>
}
else {
echo ‘<p>It is empty</p>
}
▪ In plain English, if(!empty($variable)) means “If variable is NOT empty,…”
▪ The keyword, “else” is like saying, “otherwise…”

Render command codes useless with the addslashes() function
 Add slashes will add a slash in front of the following characters:
▪
▪
▪
▪
single quote (')
double quote (")
backslash (\)
NULL
 Why is this important?
▪ Look at the following:
▪ SELECT * FROM users WHERE name='$username' AND pass='$password';
▪ If a user enters the following for his/her password…
▪ ' OR '1'='1
▪ To the database, the code now looks like this…
▪ SELECT * FROM users WHERE name='known_user' AND pass='' OR '1'='1';
▪ My question to you is: Is 1 equal to 1?
▪ The answer is, “yes”
▪ The user now has password privileges (didn’t need to know the password to get it to work
 Adding slashes renders that useless

Note: You can also remove the slashes with…
 The stripslashes() function

Note also: this is not necessary as much with an email processor, but is
critical for use with a database

Use the preg_match() function
 No, it is not a paternity test
 It stands for perform a regular expressions match

How it Works:
 int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags
[, int $offset ]]] )
 You put in a pattern (called a regular expression)
▪ A regular expression, or regex for short, is a pattern describing a certain amount of text.
 Put in a subject (the variable you want to check)
 Optional: $matches – this is a variable that will capture the results of the search
 Optional: flags – PREG_OFFSET_CAPTURE this changes the output of the
function
▪ You’re welcome to research what this does and try to figure it out.
▪ But you’re on your own for that
▪ Good luck with that!
 Optional: offset – this is in the form of a number and allows you to start the
search from a different spot

What it Does (in plain English):
 It returns the number of times $pattern matches
 If there are any errors, it returns false

Check to see if php is in a phrase
 Note the slashes surrounding the word
 The i after php indicates it’s a case insensitive search

Check for a whole word
 The \b stands for a word boundary
 It’s placed on both sides of the word, so it will only match
the word “web” (spaces on both sides)
<?php
if (preg_match("/\bweb\b/i", "PHP is the web scripting
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
language
of choice.")) {
echo "A match was found.";
"A match was found.";
} else echo
{
echo "A{ match was not found.";
} else
}
echo "A match was not found.";
?>
}
Examine the Pattern and see if you can figure out the regular
expression
 For reference, read Regular Expressions Quick Start Guide

$email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[az]{2,}$/i';
if (preg_match($email_pattern, $_POST[‘email'])) {
$email = $_POST[‘email'];
}
else {
echo '<p>There was a problem with your email
address</p>';
}

The specialcharacters() function: this converts certain
characters from the character to their html entities
 Example: $name = specialcharacters($name)
▪ & becomes &
▪ < becomes <
▪ > becomes >
 Quote Style: you can add the quote style to the function
call
▪ For example specialcharacters($name, ENT_QUOTES))
▪ ENT_QUOTES
▪ Single quotes ‘ become '
▪ Double quotes “ become "
▪ ENT_COMPAT only translates double quotes (not single quotes)
▪ Note, this is the default mode
▪ ENT_NOQUOTES neither single nor double quotes are translated

The htmlentities() function works just like special characters, but
all characters that have an html entity will be translated
 In addition to the special characters, all special entities in a particular
character set get translated
▪ © becomes ©
▪ / becomes /
▪ Etc.
 This renders all html tags useless, so links, nasty javascript, & other
meanies can’t work
The quote style option is exactly the same as the
specialcharacters() function
 You also have a character set that you can pass to the function
depending on what characters you want translated

 Default will work just fine
Your form processor should make use of a variety of validation checks
 Make sure no fields are empty
 Trim each variable with the trim() function
 Check to make sure they are not empty using the empty() function

Check the email format
 use preg_match() function (see previous slide)

Check to make sure integers are indeed integers (if you are asking
for a number)
 This isn’t necessary for the Feedback page

Sanitize your variables
 Use the htmlentities() function
 With databases, use the addslashes() method
 Note: for hopefully obvious reasons, don’t sanitize your email
variable or it won’t work as an email (the preg_match() function did
that)

If there’s any problem with the form (it’s
invalid)…
 Notify the user which fields if any are empty
▪ Let the user know were empty
 Notify the user if the email is not in the correct format
 Send the user back to the form

If there are no errors…
 Notify the user if the form was submitted properly
 Send the results using the mail() function
 Send a confirmation email

In order to write our form processor, we are going to
create our own function to keep track of errors
 Let’s call it “errorCheck()”

Goal: We want this function to…
 check to see if a field is empty
 check to see if the email field is in the incorrect format
 If either is the case, we want to add the field name to the list of
errors
 return the list of errors
When writing our own functions, we need to…
 decide what it’s going to do
 come up with a name
 errorCheck()

decide what information the function needs (this is called parameters)
 we need a list ($errors)
 we need a form field ($var)
 we need the name of the variable ($name)
▪ if a field is empty, how could we add it to the errors?

decide what information the function will produce
 return the list of errors
 using the return statement


write our code
capture the results through a function call
 create a variable that will receive the results of the function
 Formula: $variable = function($parameter1, $parameter2, etc.)
 $errors = errorCheck($errors, $_POST[‘name’], ‘name’)
First of all, write your function definition before you
call it
 before you call it, you need to have values to send to
the function (called “arguments”)

 Errors
▪ we need to create this variable first:
▪ $errors = array();
 Each field
▪ these come from the form when you click the submit button
▪ $_POST[‘name’]
 Field name
▪ you will provide these in the form of a written out string
▪ ‘name’


Goal: use preg_match to check email format
Plan the function:
 Receives:
▪ $email
 Performs:
▪ regular expression check
 Returns:
▪ false if it fails the test
▪ true if it passes the test

Call the function:
 Where is the best, most logical place to call the
function?


Goal: render all special characters that could run a command harmless
Plan the function:
 Receives:
▪ Variable ($var)
 Performs:
▪ Create a list ($pattern) of potentially harmful characters
▪ Create a list ($replacement) of html character entities
▪ Runs the preg_replace() function (http://us2.php.net/preg_replace)
 Returns:
▪ Cleaned up variable

Call the function
 Only call it if
▪ there are no empty variables AND
▪ the email format is correct
 Call it
▪ after you printed the correct results
▪ Before you run the email function



Make sure nothing is empty
Make sure the email works
If there are no empty fields Or the email is incorrect:
 Notify user there was a problem with the form
 If there are errors
▪ Display all empty fields
 If the email is incorrect
▪ Notify the user that it’s incorrect
 Include a link back to the form page

Else (no problems)
 Notify the user it was a success
 Sanitize all variables
 Run the mail() function (http://us3.php.net/mail)
GENERAL CONCEPTS

Validation Concepts:
 Why validate?
 What validation includes
 PHP v. JavaScript Validation

PHP Functions
 Built-in Functions
 User-defined Functions
PHP BUILT-IN FUNCTIONS
Trim()
 Empty()
 Preg_match()
 Preg_replace()
 html_entities()
 Htmlspecialcharacters()
 Add_slashes()
 Strip_slashes()
 Mail()

Download