You’ve gone far young padawan in your web development journey. Today, we are going to
delve into a very important language in websites. PHP is a powerful tool in web development,
and in this project we are going to make a basic validation form. There is going to be a bit of
setup, so be prepared!
In the world of web development, there are two devices to think about: The client (the computer
you are using now) and the server (the computer that holds your website).
When you learned javascript, you were running code on the client side. This means that your
code is running on your computer.
Now you are about to learn PHP, and this code can only be running on a server.
PHP has its own tag "<?php ?>" and uses some of the same rules as javascript (with a few major
differences).
The project that we will be making in this sheet is just the basics of PHP without too much of
what makes PHP unique, you will see more advanced PHP in the next web development sheet.
When you put in PHP into your website, every web page must now use ".php" as the new file
extension (including index). Another thing that you will need is a server to run your code
XAMPP is a program that turns your computer into a local server to allow you to run your php
code. It also allows you to create SQL databases (you will learn more about that in the next PHP
worksheet).
In order to run PHP code in XAMPP, you have to create your project folder in a very specific
location.
This is the folder you must make friends with.
Your project folder has to be in here.
Add a new project folder and create a new
index file (remember that the extension is
now .php).
<?php
echo "Hello, World!";
?>
Hello, World!
You’ve written your first PHP code!
In order to test your code, you have to type in "localhost/yourProjectFolder/index.php" on
your browser. You can’t just double click the file (if you do, you’ll just see the PHP code).
"echo" is the main way to output anything in PHP. (You can even output HTML elements
inside "echo", you’ll see that later).
This is part of the power of what makes PHP standout in web development. Think of the server
variable as a container with all of the information about the computer holding your site (in this
case, XAMPP)
<?php
echo "<h1>Server variable</h1>";
echo "I am running on server" . $_SERVER['SERVER_NAME'];
?>
Server variable
I am running on server: localhost
$_SERVER['SERVER_NAME'] Returns the server that your code is running on (localhost is
because you’re running on the local server on your own computer).
To access other server variables, just replace "SERVER_NAME" with whatever you need.
PHP has a very important role of passing information from the user up to the server for
processing. Of the many ways that the information is passed, the two most popular are GET and
POST.
Notice the method that the form's "method" is "get".
Also notice the URL on the left, that is the response from inputting data through the GET
method. The data is cached and displayed on the browser, this makes GET request book
markable (like bookmarking Google search results).
The URL will NOT display the information. POST is more secretive and secure when sending
log in information, updating records, or handling any confidential information.
Regular expressions (used for pattern matching) is a rather broad topic. The basic concept is that
it grabs the value given and compares it to expressions.
This is some of the basic uses of expressions. They can be combined in any number of ways to
form complex expressions on if data is inputted exactly the way you need. We won’t cover this
topic in this sheet in great detail. At this moment, just know that it exists.
This creates all variables you
need (the variables with equals
[=] between them is a PHP
feature to set multiple variables to
the same value on one line).
See the server variable in use?
This one is accessing the request
method to make sure that it is
POST (this is so that you only
have private data uploaded to the
server, and not seen on the
browser URL).
<!DOCTYPE html>
<html>
<head>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Add this code
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only constains letters and white space
if(!preg_match("/^[a-zA-Z]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
// Add this code
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Enter the highlighted code in
between the new if statement.
This checks to make sure that the
"name" input is uppercase and
lowercase letters only (that’s what
the preg_match()) is for.
The test_input() is a function you
will be writing later.
<!DOCTYPE html>
<html>
<head>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only constains letters and white space
if(!preg_match("/^[a-zA-Z]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
// Add this code
if(empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$name = test_input($_POST["email"]);
// check if email is well formed
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
// Add this code
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Add in the next section
underneath the name test.
This one checks the email input.
<!DOCTYPE html>
<html>
<head>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only constains letters and white space
if(!preg_match("/^[a-zA-Z]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if email is well formed
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
// Add this code
if(empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL is valid
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)){
$websiteErr = "Invalid URL";
}
}
// Add this code
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
This one is rather complicated, in
order to make sure the website is
valid the preg_match() will match
the expression of a website
format.
<!DOCTYPE html>
<html>
<head>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only constains letters and white space
if(!preg_match("/^[a-zA-Z]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if email is well formed
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if(empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL is valid
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)){
$websiteErr = "Invalid URL";
}
}
// Add this code
if(empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"])
}
// Add this code
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
This one is rather complicated, in
order to make sure the website is
valid the preg_match() will match
the expression of a website
format.
<!DOCTYPE html>
<html>
<head>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only constains letters and white space
if(!preg_match("/^[a-zA-Z]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if email is well formed
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if(empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL is valid
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)){
$websiteErr = "Invalid URL";
}
}
if(empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"])
}
// Add this code
if(empty($_POST["gender"])){
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"])
}
// Add this code
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only constains letters and white space
if(!preg_match("/^[a-zA-Z]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if email is well formed
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if(empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL is valid
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)){
$websiteErr = "Invalid URL";
}
}
if(empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"])
}
if(empty($_POST["gender"])){
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"])
}
}
// Add this code
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Add this code
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Right at the end of the PHP tag, add this
function
This is VITAL when inputting data through
PHP. When data is being processed, it is
possible that hackers can inject php scripts
through your input and cause havoc!
trim(): Takes away any trailing white spaces.
stripslashes(): Removes any slashes (/) from
the input. This is especially important.
htmlspecialchars(): This converts special
characters to HTML elements (this is also
used to prevent any fishy code being placed
in your input.
This was definitely a trial to get through, but you did it! You are soon reaching the ability to
allow users to log in to your website. Hopefully, you’re not scared away by PHP. Because you’ll
still have one more project to get through later!