PHP Code:: 1. HTML Forms With PHP
PHP Code:: 1. HTML Forms With PHP
Display:
Imagine we are an art supply store that sells brushes, paint, and erasers. To gather order information
from our prospective customers we will have to make a page with an HTML form to gather the
customer's order.
Note: This is an oversimplified example to educate you how to use PHP to process HTML form
information. This example is not intended nor advised to be used on a real business website.
If you need a refresher on how to properly make an HTML form, check out the HTML Form Lesson
before continuing on.
We first create an HTML form that will let our customer choose what they would like to purchase. This
file should be saved as "order.html"
order.html Code:
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form>
<select>
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input type="text" />
<input type="submit" />
</form>
</body></html>
Remember to review HTML Forms if you do not understand any of the above HTML code. Next we
must alter our HTML form to specify the PHP page we wish to send this information to. Also, we set
the method to "post".
order.html Code:
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />
</form>
</body></html>
Now that our "order.html" is complete, let us continue on and create the "process.php" file which will
process the HTML form information.
We want to get the "item" and "quantity" inputs that we have specified in our HTML form. Using an
associative array (this term is explained in the array lesson), we can get this information from the
$_POST associative array.
The proper way to get this information would be to create two new variables, $item and $quantity and
set them equal to the values that have been "posted". The name of this file is "process.php".
process.php Code:
<html><body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?>
</body></html>
As you probably noticed, the name in $_POST['name'] corresponds to the name that we specified in
our HTML form.
Now try uploading the "order.html" and "process.php" files to a PHP enabled server and test them out.
If someone selected the item brushes and specified a quantity of 6, then the following would be
displayed on "process.php":
process.php Code:
A lot of things were going on in this example. Let us step through it to be sure you understand what
was going on.
1. We first created an HTML form "order.html" that had two input fields specified, "item" and
"quantity".
2. We added two attributes to the form tag to point to "process.php" and set the method to
"post".
3. We had "process.php" get the information that was posted by setting new variables equal to
the values in the $_POST associative array.
4. We used the PHP echo function to output the customers order.
Remember, this lesson is only to teach you how to use PHP to get information from HTML forms. The
example on this page should not be used for a real business.
2. Functions
A function is just a name we give to a block of code that can be executed whenever we need it. This
might not seem like that big of an idea, but believe me, when you understand and use functions you
will be able to save a ton of time and write code that is much more readable!
For example, you might have a company motto that you have to display at least once on every
webpage. If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to
yourself, "this sounds like a situation where I might need functions."
Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn,
if you take it slow and stick with it, functions can be just minor speedbump in your programming
career. So don't give up if functions confuse you at first!
When you create a function, you first need to give it a name, like myCompanyMotto. It's with this
function name that you will be able to call upon your function, so make it easy to type and understand.
The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that.
First, you must tell PHP that you want to create a function. You do this by typing the keyword function
followed by your function name and some other stuff (which we'll talk about later).
Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the
code for myCompanyMotto.
PHP Code:
<?php
function myCompanyMotto(){
}
?>
Note: Your function name can start with a letter or underscore "_", but not a number!
With a properly formatted function in place, we can now fill in the code that we want our function to
execute. Do you see the curly braces in the above example "{ }"? These braces define where our
function's code goes. The opening curly brace "{" tells php that the function's code is starting and a
closing curly brace "}" tells PHP that our function is done!
We want our function to print out the company motto each time it's called, so that sounds like it's a job
for the echo command!
PHP Code:
<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
?>
That's it! You have written your first PHP function from scratch! Notice that the code that appears
within a function is just the same as any other PHP code.
Now that you have completed coding your PHP function, it's time to put it through a test run. Below is
a simple PHP script. Let's do two things: add the function code to it and use the function twice.
PHP Code:
<?php
echo "Welcome to Tizag.com <br />";
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
?>
<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
echo "Welcome to Tizag.com <br />";
myCompanyMotto();
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
myCompanyMotto();
?>
Display:
Welcome to Tizag.com
We deliver quantity, not quality!
Well, thanks for stopping by!
and remember...
We deliver quantity, not quality!
Although this was a simple example, it's important to understand that there is a lot going on and there
are a lot of areas to make errors. When you are creating a function, follow these simple guidelines:
Another useful thing about functions is that you can send them information that the function can then
use. Our first function myCompanyMotto isn't all that useful because all it does, and ever will do, is
print out a single, unchanging string.
However, if we were to use parameters, then we would be able to add some extra functionality! A
parameter appears with the parentheses "( )" and looks just like a normal PHP variable. Let's create a
new function that creates a custom greeting based off of a person's name.
Our parameter will be the person's name and our function will concatenate this name onto a greeting
string. Here's what the code would look like.
<?php
function myGreeting($firstName){
echo "Hello there ". $firstName . "!<br />";
}
?>
When we use our myGreeting function we have to send it a string containing someone's name,
otherwise it will break. When you add parameters, you also add more responsibility to you, the
programmer! Let's call our new function a few times with some common first names.
PHP Code:
<?php
function myGreeting($firstName){
echo "Hello there ". $firstName . "!<br />";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>
Display:
PHP Code:
<?php
function myGreeting($firstName, $lastName){
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>
Display:
Besides being able to pass functions information, you can also have them return a value. However, a
function can only return one thing, although that thing can be any integer, float, array, string, etc. that
you choose!
How does it return a value though? Well, when the function is used and finishes executing, it sort of
changes from being a function name into being a value. To capture this value you can set a variable
equal to the function. Something like:
$myVar = somefunction();
Let's demonstrate this returning of a value by using a simple function that returns the sum of two
integers.
PHP Code:
<?php
function mySum($numX, $numY){
$total = $numX + $numY;
return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";
?>
Display:
If you are new to programming, then this lesson might or might not seem like overkill. If you are
having a hard time understanding lessons, the best piece of advice would be to do your best the first
time, then be sure to come back tomorrow and next week and see if it makes anymore sense. Chances
are, after going through this tutorial more than once, with breaks in between, this topic will be
mastered.
3. Array
An array is a data structure that stores one or more values in a single value. For experienced
programmers it is important to hi that PHP's arrays are actually maps (each key is mapped to a value).
If this is your first time seeing an array, then you may not quite understand the concept of an array.
Imagine that you own a business and you want to store the names of all your employees in a PHP
variable. How would you go about this?
It wouldn't make much sense to have to store each name in its own variable. Instead, it would be nice to
store all the employee names inside of a single variable. This can be done, and we show you how
below.
PHP Code:
$employee_array[0] = "Bob";
$employee_array[1] = "Sally";
$employee_array[2] = "Charlie";
$employee_array[3] = "Clare";
In the above example we made use of the key / value structure of an array. The keys were the numbers
we specified in the array and the values were the names of the employees. Each key of an array
represents a value that we can manipulate and reference. The general form for setting the key of an
array equal to a value is:
$array[key] = value;
If we wanted to reference the values that we stored into our array, the following PHP code would get
the job done.
Note: As you may have noticed from the above code example, an array's keys start from 0 and not 1.
This is a very common problem for many new programmers who are used to counting from 1 and lead
to "off by 1" errors. This is just something that will take experience before you are fully comfortable
with it.
PHP Code:
Display:
PHP arrays are quite useful when used in conjunction with loops, which we will talk about in a later
lesson. Above we showed an example of an array that made use of integers for the keys (a numerically
indexed array). However, you can also specify a string as the key, which is referred to as an associative
array.
In an associative array a key is associated with a value. If you wanted to store the salaries of your
employees in an array, a numerically indexed array would not be the best choice. Instead, we could use
the employees names as the keys in our associative array, and the value would be their respective
salary.
PHP Code:
$salaries["Bob"] = 2000;
$salaries["Sally"] = 4000;
$salaries["Charlie"] = 600;
$salaries["Clare"] = 0;
Display:
Once again, the usefulness of arrays will become more apparent once you have knowledge of for and
while loops.
4. While loop
Repetitive tasks are always a burden to us. Deleting spam email, sealing 50 envelopes, and going to
work are all examples of tasks that are repeated. The nice thing about programming is that you can
avoid such repetitive tasks with a little bit of extra thinking. Most often these repetitive tasks are
conquered in the loop.
The idea of a loop is to do something over and over again until the task has been completed. Before we
show a real example of when you might need one, let's go over the structure of the PHP while loop.
This isn't valid PHP code, but it displays how the while loop is structured. Here is the break down of
how a while loop functions when your script is executing:
1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4) occurs.
2. The code within the while loop is executed.
3. The process starts again at (1). Effectively "looping" back.
4. If the conditional statement is false, then the code within is not executed and there is no
more looping. The code following the while loop is then executed like normal.
Imagine that you are running an art supply store. You would like to print out the price chart for number
of brushes and total cost. You sell brushes at a flat rate, but would like to display how much different
quantities would cost. This will save your customers from having to do the mental math themselves.
You know that a while loop would be perfect for this repetitive and boring task. Here is how to go
about doing it.
$brush_price = 5;
$counter = 10;
Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500
Pretty neat, huh? The loop created a new table row and its respective entries for each quantity, until our
counter variable grew past the size of 100. When it grew past 100 our conditional statement failed and
the loop stopped being used. Let's review what is going on.
1. We first made a $brush_price and $counter variable and set them equal to our desired
values.
2. The table was set up with the beginning table tag and the table headers.
3. The while loop conditional statement was checked, and $counter (10) was indeed smaller or
equal to 100.
4. The code inside the while loop was executed, creating a new table row for the price of 10
brushes.
5. We then added 10 to $counter to bring the value to 20.
6. The loop started over again at step 3, until $counter grew larger than 100.
7. After the loop had completed, we ended the table.
You may have noticed that we placed slashes infront the quotations in the first echo statement. You
have to place slashes before quotations if you do not want the quotation to act as the end of the echo
statement. This is called escaping a character and it is discussed in our PHP Strings lesson.
With proper use of loops you can complete large tasks with great ease.
5. For loop
The for loop is simply a while loop with a bit more code added to it. The common tasks that are
covered by a for loop are:
The for loop allows you to define these steps in one easy line of code. It may seem to have a strange
form, so pay close attention to the syntax used!
For Loop Example
Let us take the example from the while loop lesson and see how it could be done in a for loop. The
basic structure of the for loop is as follows:
Notice how all the steps of the loop are taken care of in the for loop statement. Each step is separated
by a semicolon: initiliaze counter, conditional statement, and the counter increment. A semicolon is
needed because these are separate expressions. However, notice that a semicolon is not needed after the
"increment counter" expression.
Here is the example of the brush prices done with a for loop .
PHP Code:
$brush_price = 5;
Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500
It is important to note that both the for loop and while loop implementation of the price chart table are
both OK at getting the job done. However, the for loop is somewhat more compact and would be
preferable in this situation. In later lessons we will see where the while loop should be used instead of
the for loop.
6. For Each
Imagine that you have an associative array that you want to iterate through. PHP provides an easy
way to use every element of an array with the Foreach statement.
While a For Loop and While Loop will continue until some condition fails, the For Each loop will
continue until it has gone through every item in the array.
We have an associative array that stores the names of people in our company as the keys with the
values being their age. We want to know how old everyone is at work so we use a Foreach loop to
print out everyone's name and age.
PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
Display:
This crazy statement roughly translates into: For each element of the $employeeAges associative array
I want to refer to the key as $key and the value as $value.
The operator "=>" represents the relationship between a key and value. You can imagine that the key
points => to the value. In our example we named the key $key and the value $value. However, it might
be easier to think of it as $name and $age. Below our example does this and notice how the output is
identical because we only changed the variable names that refer to the keys and values.
PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
Display:
7. Do While
A "do while" loop is a slightly modified version of the while loop. If you recal from one of the previous
lessons on While Loops the conditional statement is checked comes back true then the code within
the while loop is executed. If the conditional statement is false then the code within the loop is not
executed.
On the other hand, a do-while loop always executes its block of code at least once. This is because the
conditional statement is not checked until after the contained code has been executed.
A simple example that illustrates the difference between these two loop types is a conditional statement
that is always false. First the while loop:
PHP Code:
$cookies = 0;
while($cookies > 1){
echo "Mmmmm...I love cookies! *munch munch munch*";
}
Display:
As you can see, this while loop's conditional statement failed (0 is not greater than 1), which means the
code within the while loop was not executed. Now, can you guess what will happen with a do-while
loop?
PHP Code:
$cookies = 0;
do {
echo "Mmmmm...I love cookies! *munch munch munch*";
} while ($cookies > 1);
Display:
The code segment "Mmmm...I love cookies!" was executed even though the conditional statement was
false. This is because a do-while loop first do's and secondly checks the while condition!
Chances are you will not need to use a do while loop in most of your PHP programming, but it is good
to know it's there!
POST - Review
In our PHP Forms Lesson we used the post method. This is what the pertinent line of HTML code
looked like:
This HTML code specifies that the form data will be submitted to the "process.php" web page using the
POST method. The way that PHP does this is to store all the "posted" values into an associative array
called "$_POST". Be sure to take notice the names of the form data names, as they represent the keys in
the "$_POST" associative array.
Now that you know about associative arrays, the PHP code from "process.php" should make a litte
more sense.
The form names are used as the keys in the associative array, so be sure that you never have two input
items in your HTML form that have the same name. If you do, then you might see some problems
arise.
PHP - GET
As we mentioned before, the alternative to the post method is get. If we were to change our HTML
form to the get method, it would look like this:
The get method is different in that it passes the variables along to the "process.php" web page by
appending them onto the end of the URL. The URL, after clicking submit, would have this added on to
the end of it:
"?item=##&quantity=##"
The question mark "?" tells the browser that the following items are variables. Now that we changed
the method of sending information on "order.html", we must change the "process.php" code to use the
"$_GET" associative array.
$quantity = $_GET['quantity'];
$item = $_GET['item'];
After changing the array name the script will function properly. Using the get method displays the
variable information to your visitor, so be sure you are not sending password information or other
sensitive items with the get method. You would not want your visitors seeing something they are not
supposed to!
Security Precautions
Whenever you are taking user input and using you need to be sure that the input is safe. If you are
going to insert the data into a MySQL database, then you should be sure you have thought about
preventing MySQL Injection. If you are going to make a user's input available to the public, then you
should think about PHP htmlentities.
9. Magic quotes
Prior to PHP 6 there was a feature called magic quotes that was created to help protect newbie
programmers from writing bad form processing code. Magic quotes would automatically escape risky
form data that might be used for SQL Injection with a backslash \. The characters escaped by PHP
include: quote ', double quote ", backslash \ and NULL characters.
However, this newbie protection proved to cause more problems than it solved and is not in PHP 6. If
your PHP version is any version before 6 then you should use this lesson to learn more about how
magic quotes can affect you.
First things first, you need to check to see if you have magic quotes enabled on you server. The
get_magic_quotes_gpc function will return a 0 (off) or a 1 (on). These boolean values will fit nicely
into an if statement where 1 is true and 0 is false.
PHP Code:
if(get_magic_quotes_gpc())
echo "Magic quotes are enabled";
else
echo "Magic quotes are disabled";
Display:
If you received the message "Magic quotes are enabled" then you should definitely continue reading
this lesson, if not feel free to learn about it in case you are developing for servers that might have
quotes on or off.
Now lets make a simple form processor to show how machines with magic quotes enabled will escape
those potentially risky characters. This form submits to itself, so you only need to make one file,
"magic-quotes.php" to test it out.
magic-quotes.php Code:
<?php
echo "Altered Text: ".$_POST['question'];
?>
<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>
</form>
Magic quotes did a number on that string, didn't it? Notice that there is a backslash before all of those
risky characters we talked about earlier. After magic quotes:
A backslash \ becomes \\
A quote ' becomes \'
A double-quote " becomes \"
Now say that you wanted to remove the escaping that magic quotes puts in, you have two options:
disable magic quotes or strip the backslashes magic quotes adds.
magic-quotes.php Code:
<?php
echo "Removed Slashes: ";
// Remove those slashes
if(get_magic_quotes_gpc())
echo stripslashes($_POST['question']);
else
echo $_POST['question'];
?>
<form method='post'>
Question: <input type='text' name='question'/><br />
<input type='submit'>
</form>
10. Htmlentities
Whenever you allow your users to submit text to your website, you need to be careful that you don't
leave any security holes open for malicious users to exploit. If you are ever going to allow user
submitted text to be visible by the public you should consider using the htmlentities function to
prevent them from running html
The htmlentities function takes a string and returns the same string with HTML converted into HTML
entities. For example, the string "<script>" would be converted to "<script>".
By converting the < and > into entities, it prevents the browser from using it as an HTML element and
it prevents the code from running if you were to display some user's input on your website.
This may seem a little complicated, but if you think of the way a browser works, in separate stages, it
becomes a little easier. Let's look at the way the function htmlentities changes the data at three different
levels: in PHP, in raw HTML and in the web browser. The sample string is a bad script that will
redirect visitors to the malicious user's own website.
PHP Code:
If we had not used htmlentities to convert any HTML code into safe entities, this is what the raw
HTML code would be and it would have redirect a visitor to example.com.
Those two HTML code examples are what you would see if you were to view source on the web page.
However, if you were just viewing the output normally in your browser you would see the following.
Safe Display:
Dangerous Display:
You'd see whatever spammer site that the malicious user had sent you to. Probably some herbal
supplement site or weight loss pills would be displayed.
Anytime you allow users to submit content to your website, that other visitors can see, you should
consider removing the ability to let them use HTML. Although this will remove a lot of cool things that
your users can do, like making heavily customized content, it will prevent your site from a lot of
common attacks. With some custom coding you can just remove specific tags from running, but that is
beyond the scope of this lesson.
Just remember, that when allowing users to submit content to your site you are also giving them access
to your website. Be sure you take the proper precautions.
Day 02
PHP Files
1. PHP – File
Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools
for creating, uploading, and editing files.
This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After
completing this section you should have a solid understanding of all types of file manipulation in PHP!
PHP - Files: Be Careful
When you are manipulating files you must be very careful because you can do a lot of damage if you
do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage
data, and accidentally deleting a file's contents.
It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However,
we know that there are so many places where code can take a wrong turn, so we urge you to take extra
care when dealing with files in PHP.
The presentation of the file lessons will begin with how to create, open, and close a file. After
establishing those basics, we will then cover other important file tasks, such as: read, write, append,
truncate, and uploading files with PHP.
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing,
but we'll try to clarify this conundrum.
In PHP the fopen function is used to open files. However, it can also create a file if it does not find the
file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given
that you open the file for writing or appending (more on this later).
The fopen function needs two important pieces of information to operate correctly. First, we must
supply it with the name of the file that we want it to open. Secondly, we must tell the function what we
plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the
file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will
see that "testFile.txt" does not exist and will create it after running this code. There's a lot of
information in those three lines of code, let's make sure you understand it.
1. $ourFileName = "testFile.txt";
Here we create the name of our file, "testFile.txt" and store it into a PHP String variable
$ourFileName.
2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
This bit of code actually has two parts. First we use the function fopen and give it two
arguments: our file name and we inform PHP that we want to write by passing the character
"w".
Second, the fopen function returns what is called a file handle, which will allow us to
manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk
more about file handles later on.
3. fclose($ourFileHandle);
We close the file that was opened. fclose takes the file handle that is to be closed. We will talk
more about this more in the file closing lesson.
PHP - Permissions
If you are trying to get this program to run and you are having errors, you might want to check that you
have granted your PHP file access to write information to the hard drive. Setting permissions is most
often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to
allow the PHP file to write to disk, thus allowing it to create a file.
In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file
permissions.