PHP Book
PHP Book
___________________________________________________________________________________________
Introduction To PHP: ............................................................................................................................. 4
PHP - What is it? ................................................................................................................................... 4
PHP - What's it do? ............................................................................................................................... 4
What You Should Know.......................................................................................................................... 4
PHP - Necessary Setup .......................................................................................................................... 5
Installing PHP ....................................................................................................................................... 5
Installing MySQL ................................................................................................................................... 5
PHP - Syntax ........................................................................................................................................ 6
How to Save Your PHP Pages ................................................................................................................. 6
Example Simple HTML & PHP Page ......................................................................................................... 6
The Semicolon! ..................................................................................................................................... 7
White Space ......................................................................................................................................... 7
PHP - Variables ..................................................................................................................................... 8
A Quick Variable Example ...................................................................................................................... 8
PHP Variable Naming Conventions .......................................................................................................... 8
PHP - Echo ........................................................................................................................................... 8
Outputting a String ............................................................................................................................... 8
Careful When Echoing Quotes! ............................................................................................................... 9
Echoing Variables .................................................................................................................................. 9
Echoing Variables and Text Strings ....................................................................................................... 10
PHP Echo - Not a Function ................................................................................................................... 10
PHP - Strings ...................................................................................................................................... 10
PHP - String Creation .......................................................................................................................... 10
PHP - String Creation Single Quotes ..................................................................................................... 11
PHP - String Creation Double-Quotes ................................................................................................... 11
PHP - String Creation Heredoc ............................................................................................................. 12
PHP - Operators .................................................................................................................................. 12
Assignment Operators ......................................................................................................................... 12
Arithmetic Operators ........................................................................................................................... 13
Comparison Operators ......................................................................................................................... 13
String Operators ................................................................................................................................. 14
Combination Arithmetic & Assignment Operators .................................................................................. 14
Pre/Post-Increment & Pre/Post-Decrement ........................................................................................... 14
Using Comments in PHP ...................................................................................................................... 15
PHP Comment Syntax: Single Line Comment ........................................................................................ 15
PHP Comment Syntax: Multiple Line Comment ...................................................................................... 16
Good Commenting Practices ................................................................................................................ 16
PHP Include ........................................................................................................................................ 16
An Include Example ............................................................................................................................ 17
What do Visitors See? ......................................................................................................................... 17
Include Recap ..................................................................................................................................... 18
PHP Require ....................................................................................................................................... 18
Require vs Include .............................................................................................................................. 18
The If Statement ................................................................................................................................ 19
The PHP If Statement .......................................................................................................................... 19
If Statement Example ......................................................................................................................... 19
A False If Statement ........................................................................................................................... 20
If/Else Conditional Statment ................................................................................................................ 20
If/Else an Example .............................................................................................................................. 20
Execute Else Code with False ............................................................................................................... 21
PHP - Elseif ........................................................................................................................................ 21
PHP - Elseif What is it? ........................................................................................................................ 21
PHP - Using Elseif with If...Else ............................................................................................................ 22
PHP Switch Statement ......................................................................................................................... 22
PHP Switch Statement: Speedy Checking ............................................................................................. 22
PHP Switch Statement Example ........................................................................................................... 23
PHP Switch Statement: Default Case .................................................................................................... 23
Using PHP With HTML Forms ................................................................................................................ 24
Creating the HTML Form ...................................................................................................................... 24
PHP Form Processor ............................................................................................................................ 25
PHP & HTML Form Review .................................................................................................................... 26
Introduction To PHP:
If you want to learn the basics of PHP, then you've come to the right place. The goal of this tutorial is
to teach you the basics of PHP so that you can:
Customize PHP scripts that you download, so that they better fit your needs.
Begin to understand the working model of PHP, so you may begin to design your own PHP projects.
Give you a solid base in PHP, so as to make you more valuable in the eyes of future employers.
PHP stands for PHP Hypertext Preprocessor.
PHP - What is it?
Taken directly from PHP's home, PHP.net, "PHP is an HTML-embedded scripting language. Much of its
syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The
goal of the language is to allow web developers to write dynamically generated pages quickly."
This is generally a good definition of PHP. However, it does contain a lot of terms you may not be used
to. Another way to think of PHP is a powerful, behind the scenes scripting language that your visitors
won't see!
When someone visits your PHP webpage, your web server processes the PHP code. It then sees which
parts it needs to show to visitors (content and pictures) and hides the other stuff (file operations, math
calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the
webpage to your visitor's web browser.
PHP - What's it do?
It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to:
Reduce the time to create large websites.
Create a customized user experience for visitors based on information that you have gathered from
them.
Open up thousands of possibilities for online tools. Check out PHP – Hot Scripts for examples of the
great things that are possible with PHP.
Allow creation of shopping carts for e-commerce websites.
What You Should Know
Before starting this tutorial it is important that you have a basic understanding and experience in the
following:
Installing PHP
For those who are experienced enough to do this yourself, simply head over to PHP.net - Downloads
and download the most recent version of PHP.
However, if you are like most of us, you will most likely want to follow a guide to installing PHP onto
your computer. These guides are kindly provided by PHP.net based on the operating system that you
are using.
Installing MySQL
As we mentioned before, MySQL is not a requirement to use PHP, however they often go hand in hand.
Visit MySQL's MySQL Installation Guide for help on installing MySQL.
PHP - Syntax
Before we talk about PHP's syntax, let us first define what syntax is referring to.
Syntax - The rules that must be followed to write properly structured code.
PHP's syntax and semantics are similar to most other programming languages (C, Java, Perl) with the
addition that all PHP code is contained with a tag, of sorts. All PHP code must be contained within the
following...
PHP Code:
<?php
?>
<?
?>
If you are writing PHP scripts and plan on distributing them, we suggest that you use the standard
form (which includes the ?php) rather than the shorthand form. This will ensure that your scripts will
work, even when running on other servers with different settings.
How to Save Your PHP Pages
If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then you
must save the file with a .php extension, instead of the standard .html extension. So be sure to check
that you are saving your files correctly. Instead of index.html, it should be index.php if there is PHP
code in the file.
Example Simple HTML & PHP Page
Below is an example of one of the easiest PHP and HTML page that you can create and still follow web
standards.
Display:
Hello World!
If you save this file (e.g. helloworld.php) and place it on PHP enabled server and load it up in your web
browser, then you should see "Hello World!" displayed. If not, please check that you followed our
example correctly.
We used the PHP command echo to write "Hello World!" and we will be talking in greater depth about
how echo is special later on in this tutorial.
Compiled By: Shoaib Hafeez Page 6
Learn PHP By Your Self
___________________________________________________________________________________________
The Semicolon!
As you may or may not have noticed in the above example, there was a semicolon after the line of PHP
code. The semicolon signifies the end of a PHP statement and should never be forgotten. For example,
if we repeated our "Hello World!" code several times, then we would need to place a semicolon at the
end of each statement.
Display:
Hello World! Hello World! Hello World! Hello World! Hello World!
White Space
As with HTML, whitespace is ignored between PHP statements. This means it is OK to have one line of
PHP code, then 20 lines of blank space before the next line of PHP code. You can also press tab to
indent your code and the PHP interpreter will ignore those spaces as well.
Display:
Hello World!Hello World!
This is perfectly legal PHP code.
PHP Code:
<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Note for programmers: PHP does not require variables to be deNaeemd before being initialized.
PHP Variable Naming Conventions
There are a few rules that you need to follow when choosing a name for your PHP variables.
PHP variables must start with a letter or underscore "_".
PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _
Variables with more than one word should be separated with underscores. $my_variable
Variables with more than one word can also be distinguished with capitalization. $myVariable
PHP - Echo
As you saw in the previous lesson, the PHP command echo is a means of outputting text to the web
browser. Throughout your PHP career you will be using the echo command more than any other. So
let's give it a solid perusal!
Outputting a String
To output a string, like we have done in previous lessons, use PHP echo. You can place either a string
variable or you can use quotes, like we do below, to create a string that the echo function will output.
Display:
Hello!
PHP Code:
<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the
quotations by placing a backslash in front of it ( \" ). The backslash will tell PHP that you want the
quotation to be used within the string and NOT to be used to end echo's string.
Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the common task
of echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold
a string. Below is the correct format for echoing a variable.
Display:
Hello Bilal. My name is: 4a
PHP Code:
<?php
$my_string = "Hello Bilal. My name is: ";
$newline = "<br />";
echo $my_string."Bilalettta".$newline;
echo "Hi, I'm Bilal. Who are you? ".$my_string.$newline;
echo "Hi, I'm Bilal. Who are you? ".$my_string."Bilaletta";
?>
Display:
Hello Bilal. My name is: Bilaletta
Hi, I'm Bilal. Who are you? Hello Bilal. My name is:
Hi, I'm Bilal. Who are you? Hello Bilal. My name is: Bilaletta
This combination can be done multiple times, as the example shows. This method of joining two or
more strings together is called concatenation and we will talk more about this and other forms of
string manipulation in our string lesson.
PHP Echo - Not a Function
Echo is not a function, rather it is a language construct. When you use functions in PHP, they have a
very particular form, which we will be going over later. For now, just know that echo is a special tool
that you'll come to know and love!
PHP - Strings
In the last lesson, PHP Echo, we used strings a bit, but didn't talk about them in depth. Throughout
your PHP career you will be using strings a great deal, so it is important to have a basic understanding
of PHP strings.
PHP - String Creation
Before you can use a string you have to create it! A string can be used directly in a function or it can
be stored in a variable. Below we create the exact same string twice: first storing it into a variable and
in the second case we send the string directly to echo.
In the above example the first string will be stored into the variable $my_string, while the second
string will be used in the echo and not be stored. Remember to save your strings into variables if you
plan on using them more than once! Below is the output from our example code. They look identical
just as we thought.
Display:
Shoaib & Shakeel - Unlock your potential! Shoaib & Shakeel - Unlock your potential!
PHP Code:
$my_string = 'Shoaib & Shakeel - Unlock your potential!';
echo 'Shoaib & Shakeel - Unlock your potential!';
echo $my_string;
If you want to use a single-quote within the string you have to escape the single-quote with a
backslash \ . Like this: \' !
PHP Code:
echo 'Shoaib & Shakeel - It\'s Neat!';
PHP Code:
$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the
backslash will show up when you output the string.
These escaped characters are not very useful for outputting to a web page because HTML ignore extra
white space. A tab, newline, and carriage return are all examples of extra (ignorable) white space.
However, when writing to a file that may be read by human eyes these escaped characters are a
valuable tool!
PHP Code:
$my_string = <<<TEST
Shoaib & Shakeel.com
Webmaster Tutorials
Unlock your potential!
TEST;
echo $my_string;
There are a few very important things to remember when using heredoc.
Use <<< and some identifier that you choose to begin the heredoc. In this example we chose TEST as
our identifier. Repeat the identifier followed by a semicolon to end the heredoc string creation. In this
example that was TEST; The closing sequence TEST; must occur on a line by itself and cannot be
indented! Another thing to note is that when you output this multi-line string to a web page, it will not
span multiple lines because we did not have any <br /> tags contained inside our string! Here is the
output made from the code above.
Display:
Shoaib & Shakeel.com Webmaster Tutorials Unlock your potential!
Once again, take great care in following the heredoc creation guidelines to avoid any headaches.
PHP - Operators
In all programming languages, operators are used to manipulate or perform operations on variables
and values. You have already seen the string concatenation operator "." in the Echo Lesson and the
assignment operator "=" in pretty much every PHP example so far.
There are many operators used in PHP, so we have separated them into the following categories to
make it easier to learn them all.
Assignment Operators
Arithmetic Operators
Comparison Operators
String Operators
Combination Arithmetic & Assignment Operators
Assignment Operators
Assignment operators are used to set a variable equal to a value or set a variable to another variable's
value. Such an assignment of value is done with the "=", or equal character. Example:
$my_var = 4;
$another_var = $my_var;
Now both $my_var and $another_var contain the value 4. Assignments can also be used in
conjunction with arithmetic operators.
PHP Code:
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiplication = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo "Perform addition: 2 + 4 = ".$addition."<br />";
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />";
echo "Perform multiplication: 5 * 3 = ".$multiplication."<br />";
echo "Perform division: 15 / 3 = ".$division."<br />";
echo "Perform modulus: 5 % 2 = " . $modulus
. ". Modulus is the remainder after the division operation has been performed.
In this case it was 5 / 2, which has a remainder of 1.";
Display:
Perform addition: 2 + 4 = 6
Perform subtraction: 6 - 2 = 4
Perform multiplication: 5 * 3 = 15
Perform division: 15 / 3 = 5
Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed. In
this case it was 5 / 2, which has a remainder of 1.
Comparison Operators
Comparisons are used to check the relationship between variables and/or values. If you would like to
see a simple example of a comparison operator in action, check out our If Statement Lesson.
Comparison operators are used inside conditional statements and evaluate to either true or false. Here
are the most important comparison operators of PHP.
Assume: $x = 4 and $y = 5;
PHP Code:
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";
Display:
Hello Billy!
In addition to this "shorterhand" technique, you can specify whether you want to increment before the
line of code is being executed or after the line has executed. Our PHP code below will display the
difference.
Display:
The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5
As you can see the value of $x++ is not reflected in the echoed text because the variable is not
incremented until after the line of code is executed. However, with the pre-increment "++$x" the
variable does reflect the addition immediately.
In HTML a comment's main purpose is to serve as a note to you, the web developer or to others who
may view your website's source code. However, PHP's comments are different in that they will not be
displayed to your visitors. The only way to view PHP comments is to open the PHP file for editing. This
makes PHP comments only useful to PHP programmers.
In case you forgot what an HTML comment looked like, see our example below.
HTML Code:
<!-- This is an HTML Comment -->
PHP Code:
<?php
echo "Hello World!"; // This will print out Hello World!
echo "<br />Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
# echo "I don't do anything either";
?>
Notice that a couple of our echo statements were not evaluated because we commented them out with
the single line comment. This type of line commenting is often used for quick notes about complex and
confusing code or to temporarily remove a line of PHP code.
PHP Code:
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>
Display:
Hello World!
Let the comments permeate your code and you will be a happier PHPer in the future. Use single line
comments for quick notes about a tricky part in your code and use multiple line comments when you
need to describe something in greater depth than a simple note.
PHP Include
Without understanding much about the details of PHP, you can save yourself a great deal of time with
the use of the PHP include command. include takes a file name and simply inserts that file's contents
into the script that issued the include command.
Why is this a cool thing? Well, first of all, this means that you can type up a common header or menu
file that you want all your web pages to include. When you add a new page to your site, instead of
having to update the links on several web pages, you can simply change the Menu file.
menu.php Code:
<html>
<body>
<a href="http://www.example.com/index.php">Home</a> -
<a href="http://www.example.com/about.php">About Us</a> -
<a href="http://www.example.com/links.php">Links</a> -
<a href="http://www.example.com/contact.php">Contact Us</a> <br />
Save the above file as "menu.php". Now create a new file, "index.php" in the same directory as
"menu.php". Here we will take advantage of the include command to add our common menu.
index.php Code:
<?php include("menu.php"); ?>
<p>This is my home page that uses a common menu to save me time when I add
new pages to my website!</p>
</body>
</html>
Display:
Home - About Us - Links - Contact Us
This is my home page that uses a common menu to save me time when I add new pages to my website!
And we would do the same thing for "about.php", "links.php", and "contact.php". Just think how
terrible it would be if you had 15 or more pages with a common menu and you decided to add another
web page to that site. You would have to go in and manually edit every single file to add this new
page, but with include files you simply have to change "menu.php" and all your problems are solved.
Avoid such troublesome occasions with a simple include file.
Include Recap
The include command simply takes all the text that exists in the specified file and copies it into the file
that uses the include command. Include is quite useful when you want to include the same PHP, HTML,
or text segment on multiple pages of a website. The include command is used widely by PHP web
developers. Like PHP Echo, include is not a function, but a language construct.
The next lesson will talk about a slight variation of the include command: require. It is often best to
use the require command instead of the include command in your PHP Code. Read the next lesson to
find out why!
PHP Require
Just like the previous lesson, the require command is used to include a file into your PHP code.
However there is one huge difference between the two commands, though it might not seem that big
of a deal.
Require vs Include
When you include a file with the include command and PHP cannot find it you will see an error
message like the following:
PHP Code:
<?php
include("noFileExistsHere.php");
echo "Hello World!";
?>
Display:
Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in
/home/websiteName/FolderName/Shoaib & ShakeelScript.php on line 2 Warning: main(): Failed
opening 'noFileExistsHere.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/websiteName/FolderName/Shoaib & ShakeelScript.php on line 2
Hello World!
Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP
script from running. On the other hand, if we did the same example but used the require statement we
would get something like the following example.
PHP Code:
<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>
The echo statement was not executed because our script execution died after the require command
returned a fatal error! We recommend that you use require instead of include because your scripts
should not be executing if necessary files are missing or misnamed.
The If Statement
The PHP if statement is very similar to other programming languages use of the if statement, but for
those who are not familiar with it, picture the following:
Think about the decisions you make before you go to sleep. If you have something to do the next day,
say go to work, school, or an appointment, then you will set your alarm clock to wake you up.
Otherwise, you will sleep in as long as you like!
This simple kind of if/then statement is very common in every day life and also appears in
programming quite often. Whenever you want to make a decision given that something is true (you
have something to do tomorrow) and be sure that you take the appropriate action, you are using an
if/then relationship.
The PHP If Statement
The if statement is necessary for most programming, thus it is important in PHP. Imagine that on
January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the
use of PHP if statements you could have this process automated, months in advance, occuring every
year on January 1st.
This idea of planning for future events is something you would never have had the opportunity of
doing if you had just stuck with HTML.
If Statement Example
The "Happy New Year" example would be a little difficult for you to do right now, so let us instead start
off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a
segment of code will be executed. See the example below for the form of a PHP if statement.
PHP Code:
$my_name = "someguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";
Display:
Your name is someguy!
Welcome to my homepage!
Did you get that we were comparing the variable $my_name with "someguy" to see if they were
equal? In PHP you use the double equal sign (==) to compare values. Additionally, notice that because
the if statement turned out to be true, the code segment was executed, printing out "Your name is
someguy!". Let's go a bit more in-depth into this example to iron out the details.
We first set the variable $my_name equal to "someguy".
PHP Code:
$my_name = "anotherguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";
Display:
Welcome to my homepage!
Here the variable contained the value "anotherguy", which is not equal to "someguy". The if statement
evaluated to false, so the code segment of the if statement was not executed. When used properly, the
if statement is a powerful tool to have in your programming arsenal!
If/Else Conditional Statment
Has someone ever told you, "if you work hard, then you will succeed"? And what happens if you do not
work hard? Well, you fail! This is an example of an if/else conditional statement.
If you work hard then you will succeed.
Else, if you do not work hard, then you will fail.
How does this translate into something useful for PHP developers? Well consider this:
Someone comes to your website and you want to ask this visitor her name if it is her first time coming
to your site. With an if statement this is easy. Simply have a conditional statement to check, "are you
visiting for the first time". If the condition is true, then take them to the "Insert Your Name" page, else
let her view the website as normal because you have already asked her for her name in the past.
If/Else an Example
Using these conditional statements can add a new layers of "cool" to your website. Here's the basic
form of an if/else statement in PHP.
PHP Code:
$number_three = 3;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";}
PHP Code:
$number_three = 421;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}
Display:
The if statement evaluated to false
The variable was set to 421, which is not equal to 3 and the if statement was false. As you can see,
the code segment contained within the else was used in this case.
PHP - Elseif
An if/else statement is great if you only need to check for one condition. However, what would you do
if you wanted to check if your $employee variable was the company owner Bilal, the Vice President Ms.
Tanner, or a regular employee? To check for these different conditions you would need the elseif
statement.
PHP - Elseif What is it?
An if statement is made up of the keyword "if" and a conditional statement (i.e. $name == "Ted").
Just like an if statement, an elseif statement also contains a conditional statement, but it must be
preceded by an if statement. You cannot have an elseif statement without first having an if statement.
When PHP evaluates your If...elseif...else statement it will first see if the If statement is true. If that
tests comes out false it will then check the first elseif statement. If that is false it will either check the
next elseif statement, or if there are no more elseif statements, it will evaluate the else segment, if
one exists (I don't think I've ever used the word "if" so much in my entire life!). Let's take a look at a
real world example.
PHP Code:
$employee = "Bilal";
if($employee == "Ms. Tanner"){
echo "Hello Ma'am";
} else {
echo "Morning";
}
Now, if we wanted to also check to see if the big boss Bilal was the employee we need to insert an
elseif clause.
PHP Code:
$employee = "Bilal";
if($employee == "Ms. Tanner"){
echo "Hello Ma'am";
} elseif($employee == "Bilal"){
echo "Good Morning Sir!";
}else {
echo "Morning";
}
Display:
Good Morning Sir!
PHP first checked to see if $employee was equal to "Ms. Tanner", which evaluated to false. Next, PHP
checked the first elseif statement. $employee did in fact equal "Bilal" so the phrase "Good Morning
Sir!" was printed out. If we wanted to check for more employee names we could insert more elseif
statements!
Remember that an elseif statement cannot be used unless it is preceded by an if statement!
PHP Code:
$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
}
Display:
Traveling to Tokyo
Bring lots of money
The value of $destination was Tokyo, so when PHP performed the switch operating on $destination in
immediately did a search for a case with the value of "Tokyo". It found it and proceeded to execute the
code that existed within that segment.
You might have noticed how each case contains a break; at the end of its code area. This break
prevents the other cases from being executed. If the above example did not have any break
statements then all the cases that follow Tokyo would have been executed as well. Use this knowledge
to enhance the power of your switch statements!
The form of the switch statement is rather unique, so spend some time reviewing it before moving on.
Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.
PHP Switch Statement: Default Case
You may have noticed the lack of a place for code when the variable doesn't match our condition. The
if statement has the else clause and the switch statement has the default case.
It's usually a good idea to always include the default case in all your switch statements. Below is a
variation of our example that will result in none of the cases being used causing our switch statement
to fall back and use the default case.
Note: there is no case before default.
Display:
Traveling to New York
Bring lots of underwear!
order.html Code:
<html><body>
<h4>Shoaib & Shakeel 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>
Display:
order.html Code:
<html><body>
<h4>Shoaib & Shakeel 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.
PHP Form Processor
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".
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Shoaib & Shakeel 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:
You ordered 6 brushes.
Thank you for ordering from Shoaib & Shakeel Art Supplies!
PHP - 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 you functions confuse you at first!
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.
Using Your PHP Function
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 Shoaib & Shakeel.com <br />";
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
?>
Display:
Welcome to Shoaib & Shakeel.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:
Always start your function with the keyword function
Remember that your function's code must be between the "{" and the "}"
When you are using your function, be sure you spell the function name correctly
Don't give up!
PHP Functions - Parameters
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.
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.
Display:
Hello there Ali!
Hello there Ahmed!
Hello there Javed!
Hello there Kashif!
It is also possible to have multiple parameters in a function. To separate multiple parameters PHP uses
a comma ",". Let's modify our function to also include last names.
PHP Code:
<?php
function myGreeting($firstName, $lastName){
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myGreeting("Ali", "Khan");
myGreeting("Ahmed", "Bilgrami");
myGreeting("Javed", "Iqbal");
myGreeting("Kashif", "Jibran");
?>
Display:
Hello there Ali Khan!
Hello there Ahmed Bilgrami!
Hello there Javed Iqbal!
Hello there Kashif Jibran!
Display:
Before the function, myNumber = 0
After the function, myNumber = 7
When we first print out the value of $myNumber it is still set to the original value of 0. However, when
we set $myNumber equal to the function mySum, $myNumber is set equal to mySum's result. In this
case, the result was 3 + 4 = 7, which was successfully stored into $myNumber and displayed in the
second echo statement!
PHP Functions - Practice Makes Perfect
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.
PHP Array
An array is a data structure that stores one or more values in a single value. For experienced
programmers it is important to note that PHP's arrays are actually maps (each key is mapped to a
value).
PHP - A Numerically Indexed Array
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] = "Bilal";
$employee_array[1] = "Sohail";
$employee_array[2] = "Anwer";
$employee_array[3] = "Naeem";
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;
PHP Code:
echo "Two of my employees are "
. $employee_array[0] . " & " . $employee_array[1];
echo "<br />Two more employees of mine are "
. $employee_array[2] . " & " . $employee_array[3];
Display:
Two of my employees are Bilal & Sohail
Two more employees of mine are Anwer & Naeem
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.
PHP - Associative Arrays
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["Bilal"] = 2000;
$salaries["Sohail"] = 4000;
$salaries["Anwer"] = 600;
$salaries["Naeem"] = 0;
Display:
Bilal is being paid - $2000
Sohail is being paid - $4000
Anwer is being paid - $600
Naeem is being paid - $0
Once again, the usefulness of arrays will become more apparent once you have knowledge of for and
while loops.
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.
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.
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!
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.
PHP Code:
$employeeAges;
$employeeAges["Latif"] = "28";
$employeeAges["Ali"] = "16";
$employeeAges["Rehan"] = "35";
$employeeAges["Raheel"] = "46";
$employeeAges["Gul Sher"] = "34";
Display:
Name: Latif, Age: 28
Name: Ali, Age: 16
Name: Rehan, Age: 35
Name: Raheel, Age: 46
Name: Gul Sher, Age: 34
The syntax of the foreach statement is a little strange, so let's talk about it some.
Foreach Syntax: $something as $key => $value
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["Latif"] = "28";
$employeeAges["Ali"] = "16";
$employeeAges["Rehan"] = "35";
$employeeAges["Raheel"] = "46";
$employeeAges["Gul Sher"] = "34";
Display:
Name: Latif, Age: 28
Name: Ali, Age: 16
Name: Rehan, Age: 35
Name: Raheel, Age: 46
Name: Gul Sher, Age: 34
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:
Mmmmm...I love cookies! *munch munch munch*
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!
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.
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!
PHP Code:
if(get_magic_quotes_gpc())
echo "Magic quotes are enabled";
else
echo "Magic quotes are disabled";
Display:
Magic quotes are enabled
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.
Magic Quotes in Action
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>
This simple form will display to you what magic quotes is doing. If you were to enter and submit the
string: Sandy said, "It's a beautiful day outside and I like to use \'s." You would receive the following
output.
Question:
Submit Query
Bottom of 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.
Removing Backslashes - stripslashes()
Before you use PHP's backslash removal function stripslashes it's smart to add some magic quote
checking like our "Are They Enabled?" section above. This way you won't accidentally be removing
slashes that are legitimate in the future if your PHP's magic quotes setting changes in the future.
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>
Our new output for our string containing risky characters would now be:
Display:
Removed Slashes: Sandy said, "It's a beautiful day outside and I like to use \'s."
Question:
Submit Query
PHP Code:
// An imaginary article submission from a bad user
// it will redirect anyone to example.com if the code is run in a browser
$userInput = "I am going to hax0r your site, hahaha!
<script type='text/javascript'>
window.location = 'http://www.example.com/'
</script>'";
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:
I am going to hax0r your site, hahaha! <script type='text/javascript'> window.location =
'http://www.example.com/' </script>'
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.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
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 Shoaib & Shakeel.com will have a more in-depth tutorial on how to use CHMOD to
set file permissions.
PHP - File Open
In the previous lesson we used the function fopen to create a new file. In this lesson we will be going
into the details of this important function and see what it has to offer.
PHP - Different Ways to Open a File
For many different technical reasons, PHP requires you to specify your intentions when you open a file.
Below are the three basic ways to open a file and the corresponding character that PHP uses.
Read: 'r'
Open a file for read only use. The file pointer begins at the front of the file.
Write: 'w’
Open a file for write only use. In addition, the data in the file is erased and you will begin writing data
at the beginning of the file. This is also called truncating a file, which we will talk about more in a later
lesson. The file pointer begins at the start of the file.
Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data
at the end of the file. The file pointer begins at the end of the file.A file pointer is PHP's way of
remembering its location in a file. When you open a file for reading, the file pointer begins at the start
of the file. This makes sense because you will usually be reading data from the front of the file.
However, when you open a file for appending, the file pointer is at the end of the file, as you most
likely will be appending data at the end of the file. When you use reading or writing functions they
begin at the location specified by the file pointer.
Compiled By: Shoaib Hafeez Page 42
Learn PHP By Your Self
___________________________________________________________________________________________
PHP - Explanation of Different Types of fopen
These three basic ways to open a file have distinct purposes. If you want to get information out of a
file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file
with the "w" option. This would wipe clean all existing data within the file.
If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to
append the data on to the end. This would be the "a" option.
PHP - File Open: Advanced
There are additional ways to open a file. Above we stated the standard ways to open a file. However,
you can open a file in such a way that reading and writing is allowable! This combination is done by
placing a plus sign "+" after the file mode character.
Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
Write/Read: ' w+'
This is exactly the same as r+, except that it deletes all information in the file when the file is opened.
Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file.
PHP - File Open: Cookie Cutter
Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above
(i.e. r, w, a, etc).
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The function fclose requires the file handle that we want to close down. In our example we set our
variable "$fileHandle" equal to the file handle returned by the fopen function.
After a file has been closed down with fclose it is impossible to read, write or append to that file unless
it is once more opened up with the fopen function.
PHP - File Write
Now that you know how to open and close a file, lets get on to the most useful part of file
manipulation, writing! There is really only one main function that is used to write and it's logically
called fwrite.
PHP - File Open: Write
Before we can write information to our test file we have to use the function fopen to open the file for
writing.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bilalby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer,
which for writing, starts out at the beginning of the file.
We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData
that first contained Bilalby Bopper and second contained Tracy Tanner. After we finished writing we
closed the file using the fclose function.
If you were to open the testFile.txt file in NOTEPAD it would look like this:
Compiled By: Shoaib Hafeez Page 44
Learn PHP By Your Self
___________________________________________________________________________________________
Contents of the testFile.txt File:
Bilal by Bopper
Tracy Tanner
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Welcome\n";
fwrite($fh, $stringData);
$stringData = "to PHP\n";
fwrite($fh, $stringData);
fclose($fh);
If you now open the testFile.txt file you will see that Bilalby and Tracy have both vanished, as we
expected, and only the data we just wrote is present.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
The file we created in the last lesson was named "testFile.txt". Your PHP script that you are writing
should reside in the same directory as "text.txt". Here are the contents of our file from File Write.
testFile.txt Contents:
Welcome
to PHP
Now that the file is open, with read permissions enabled, we can get started!
PHP - File Read: fread Function
The fread function is the staple for getting data out of a file. The function requires a file handle, which
we have, and an integer to tell the function how much data, in bytes, it is supposed to read.
One character is equal to one byte. If you wanted to read the first five characters then you would use
five as the integer.
Compiled By: Shoaib Hafeez Page 45
Learn PHP By Your Self
___________________________________________________________________________________________
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 3);
fclose($fh);
echo $theData;
Display:
Wel
The first five characters from the testFile.txt file are now stored inside $theData. You could echo this
string, $theData, or write it to another file.
If you wanted to read all the data from the file, then you need to get the size of the file. The filesize
function returns the length of a file, in bytes, which is just what we need! The filesize function requires
the name of the file that is to be sized up.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
Display:
Welcome to PHP
Note: It is all on one line because our "testFile.txt" file did not have a <br /> tag to create an HTML
line break. Now the entire contents of the testFile.txt file is stored in the string variable $theData.
PHP - File Read: gets Function
PHP also lets you read a line of data at a time from a file with the gets function. This can or cannot be
useful to you, the programmer. If you had separated your data with new lines then you could read in
one segment of data at a time with the gets function.
Lucky for us our "testFile.txt" file is separated by new lines and we can utilize this function.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
testFile.txt Contents:
Welcome
The fgets function searches for the first occurrence of "\n" the newline character. If you did not write
newline characters to your file as we have done in File Write, then this function might not work the
way you expect it to.
PHP - File Delete
You know how to create a file. You know how to open a file in an assortment of different ways. You
even know how to read and write data from a file!
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just
needs to know the name of the file to start working its destructive magic.
PHP Code:
$myFile = "testFile.txt";
unlink($myFile);
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson.
The only thing that is different is that the file pointer is placed at the end of the file in append mode,
so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);
HTML Code:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
Display:
Upload File
Choose a file to upload:
Bottom of Form
After the user clicks submit, the data will be posted to the server and the user will be redirected to
uploader.php. This PHP file is going to process the form data and do all the work.
PHP - File Upload: What's the PHP Going to Do?
Now that we have the right HTML form we can begin to code the PHP script that is going to handle our
uploads. Typically, the PHP file should make a key decision with all uploads: keep the file or throw it
away. A file might be thrown away from many reasons, including:
The file is too large and you do not want to have it on your server.
You wanted the person to upload a picture and they uploaded something else, like an executable file
(.exe).
There were problems uploading the file and so you can't keep it.
This example is very simple and omits the code that would add such functionality.
PHP Code:
// Where the file is going to be placed
$target_path = "uploads/";
NOTE: You will need to create a new directory in the directory where uploader.php resides, called
"uploads", as we are going to be saving files there.
We now have all we need to successfully save our file to the server. $target_path contains the path
where we want to save our file to.
PHP - File Upload: move_uploaded_file Function
Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The
move_uploaded_file function needs to know 1) The path of the temporary file (check!) 2) The path
where it is to be moved to (check!).
PHP Code:
$target_path = "uploads/";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
If the upload is successful, then you will see the text "The file filename has been uploaded". This is
because $move_uploaded_file returns true if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error uploading the file, please try
again!" would be displayed.
PHP Code:
$numberedString = "1234567890"; // 10 numbers from 1 to 0
Display:
The position of 5 in our string was 4
Notice that the position is 4, which may seem confusing at first, until you realize that PHP starts
counting from 0.
The number 1 - Position 0 - No match
The number 2 - Position 1 - No match
The number 3 - Position 2 - No match
The number 4 - Position 3 - No match
The number 5 - Position 4 - Match
Although we only searched for a single character, you can use this function to search for a string with
any number of characters. Also, it is important to note that this function will return the position of the
start of the first match. So if we had searched the same string for "567890" we would again find a
match and position 4 because that is where the match starts.
PHP Code:
$numberedString = "1234567890123456789012345678901234567890";
Display:
The position of 5 in our string was 4
The position of the second 5 was 14
By taking the first match's position of 4 and adding 1 we then asked strpos to begin searching after
the last match. The string it was actually searching after computing the offset was: 6789012345...
Letting us find the second 5 in the string.
If we use our knowledge of PHP While Loops we can find every single 5 in our string numberedString
with just a few lines of code.
PHP Code:
$numberedString = "1234567890123456789012345678901234567890";
$offset = 0; // initial offset is 0
$fiveCounter = 0;
Display:
Five #1 is at position - 4
Five #2 is at position - 14
Five #3 is at position - 24
Five #4 is at position - 34
That conditional statement in our while loop may look a little intimidating, but not if you break it down.
$offset = strpos($numberedString, "5", $offset + 1) - This is our conditional statement for our PHP
While Loop. If this ever is false the while loop will stop running. This conditional statement always runs
before each pass through the while loop.
strpos($numberedString, "5", $offset + 1) - This is the same code we used in a previous example. We
are going to search our string numberedString for the number 5 and use the last match's value (stored
1. search - This is what you want to search your string for. This can be a string or an array.
2. replace - All matches for search will be replaced with this value. This can be a string or an array.
3. originalString - This is what search and replace will be operating on. The str_replace function will
return a modified version of originalString when it completes.
PHP Code:
//string that needs to be customized
$rawstring = "Welcome Birmingham parents. Your replaceme is a pleasure to have!";
//male string
$malestr = str_replace("replaceme", "son", $rawstring);
//female string
$femalestr = str_replace("replaceme", "daughter", $rawstring);
Display:
Son: Welcome Birmingham parents. Your son is a pleasure to have!
Daughter: Welcome Birmingham parents. Your daughter is a pleasure to have!
With these two gender customized strings created we could then provide a more engaging experience
for the student's parents when they logged into the school website with their kid's credentials.
str_replace Arrays: Multiple Replaces in One
In the last example we only needed to replace one word replaceme in our string, but what if we
wanted to replace many words? We could just use the function multiple times to get the job done, or
we could create an array of placeholders and a second array of replace values to get it all done in one
function call.
PHP Code:
//string that needs to be customized
$rawstring = "Welcome Birmingham parent! <br />
Your offspring is a pleasure to have!
We believe pronoun is learning a lot.<br />
The faculty simple adores pronoun2 and you can often hear
them say \"Attah sex!\"<br />";
//placeholders array
$placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex');
//male replace values array
$malevals = array('son', 'he', 'him', 'boy');
//female replace values array
$femalevals = array('daughter', 'she', 'her', 'girl');
//male string
$malestr = str_replace($placeholders, $malevals, $rawstring);
//female string
$femalestr = str_replace($placeholders, $femalevals, $rawstring);
Display:
Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores he2 and you can often hear them say "Attah boy!"
PHP Code:
// ...snip
//placeholders array
$placeholders = array('offspring', 'pronoun2', 'pronoun', 'sex');
//male replace values array
$malevals = array('son', 'him', 'he', 'boy');
//female replace values array
$femalevals = array('daughter', 'her', 'she', 'girl');
//snip...
1. original string - This is your original string that will be operated on.
2. replacement string - This string will be used to replace everything in the string from the
starting point to the ending point (specified by length).
3. starting point - This is the place in the original string that will be used to mark the
replacement's beginning. A negative value specifies the number of characters from the end of
the string.
4. optional length - How many characters from the original string will be replaced. If no length is
specified then the end of the string is used. If a value of 0 is used then no characters will be
replaced and an insert is performed. A negative value specifies the number of characters from
the end of the string.
PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";
//starting point 5
$sp5 = substr_replace($original, "Five", 5);
//starting point 12
$sp12 = substr_replace($original, "Twelve", 12);
//starting point 0
$sp0 = substr_replace($original, "Zero", 0);
//starting point -1
$spneg1 = substr_replace($original, "Negative 1", -1);
PHP Code:
//string that needs to be customized
$original = "ABC123 Hello Mr. Cow! DEF321";
Display:
Original String: ABC123 Hello Mr. Cow! DEF321
Clean #1: Hello Mr. Cow! DEF321
Clean #2: Hello Mr. Cow!
Make sure that you play around with this function some on your own so you can get a feel for how the
starting point and length parameters effect this function.
substr_replace Perform an Insert
By setting the length parameter to zero you can stop substr_replace from removing anything from the
original string and just add to it. If we wanted to add a second and third person to our $original string
PHP Code:
//string that needs to be customized
$original = "Hello Mr. Cow!";
// Find where Mr. Cow ends by adding the length of Mr. Cow
$cowpos_end = $cowpos + strlen("Mr. Cow");
Display:
Original String: Hello Mr. Cow!
After Mrs. Bear: Hello Mr. Cow and Mrs. Bear!
After Sensei Shark: Hello Sensei Shark, Mr. Cow and Mrs. Bear!
We snuck a new function strlen into that example, but it isn't that complicated of a function, as it
stands for "string length."
$cowpos_end = $cowpos + strlen("Mr. Cow");
The strlen function takes a string and then counts up how many characters are in it then returns that
number. So by calculating the length of "Mr. Cow" and adding that to the position, we find out where
the end point is!
PHP - String Capitalization Functions
If you've ever wanted to manipulate the capitalization of your PHP strings, then this lesson will be
quite helpful to you. PHP has three primary capitalization related functions: strtoupper, strtolower and
ucwords. The function names are pretty self-explanatory, but why they are useful in programming
might be new to you.
Converting a String to Upper Case - strtoupper
The strtoupper function takes one argument, the string you want converted to upper case and returns
the converted string. Only letters of the alphabet are changed, numbers will remain the same.
PHP Code:
$originalString = "String Capitalization 1234";
$upperCase = strtoupper($originalString);
echo "Old string - $originalString <br />";
echo "New String - $upperCase";
PHP Code:
$originalString = "String Capitalization 1234";
$lowerCase = strtolower($originalString);
echo "Old string - $originalString <br />";
echo "New String - $lowerCase";
Display:
Old string - String Capitalization 1234
New String - string capitalization 1234
PHP Code:
$titleString = "a title that could use some hELP";
$ucTitleString = ucwords($titleString);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";
Display:
Old title - a title that could use some hELP
New title - A Title That Could Use Some HELP
Notice that the last word "hELP" did not have the capitalization changed on the letters that weren't
first, they remained capitalized. If you want to ensure that only the first letter is capitalized in each
word of your title, first use the strtolower function and then the ucwords function.
PHP Code:
$titleString = "a title that could use some hELP";
$lowercaseTitle = strtolower($titleString);
$ucTitleString = ucwords($lowercaseTitle);
echo "Old title - $titleString <br />";
echo "New title - $ucTitleString";
1. Hello,
2. I
3. would
4. like
5. to
6. lose
7. weight.
The dynamite (the space character) disappears, but the other stuff remains, but in pieces. With that
abstract picture of the explode function in mind, lets take a look at how it really works.
The explode Function
The first argument that explode takes is the delimiter (our dynamite) which is used to blow up the
second argument, the original string. explode returns an array of string pieces from the original and
they are numbered in order, starting from 0. Lets take a phone number in the form ###-###-####
and use a hyphen "-" as our dynamite to split the string into three separate chunks.
PHP Code:
$rawPhoneNumber = "800-555-5555";
Display:
Raw Phone Number = 800-555-5555
First chunk = 800
Second chunk = 555
Third Chunk chunk = 5555
Display:
Piece 0 = Please
Piece 1 = don't
Piece 2 = blow
Piece 3 = me
Piece 4 = to
Piece 5 = pieces.
Limited Piece 0 = Please
Limited Piece 1 = don't
Limited Piece 2 = blow
Limited Piece 3 = me to pieces.
The limited explosion has 4 pieces (starting from 0, ending at 3). If you forgot how a for loop works,
check out PHP For Loops.
PHP - Array implode
The PHP function implode operates on an array and is known as the "undo" function of explode. If you
have used explode to break up a string into chunks or just have an array of stuff you can use implode
to put them all into one string.
PHP implode - Repairing the Damage
The first argument of implode is the string of characters you want to use to join the array pieces
together. The second argument is the array (pieces).
PHP Code:
$pieces = array("Hello", "World,", "I", "am", "Here!");
Display:
Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!
The implode function will convert the entire array into a string and there is no optional argument to
limit this as there was in the explode function.
PHP Code:
<?php
echo date("m/d/y");
?>
If the 2010 Winter Olympics were just finishing up, you would see something like:
Display:
02/27/10
Be sure to test this out on your own PHP enabled server, it's really great to see the instant results
available with PHP date!
PHP Code:
<?php
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
echo "Tomorrow is ".date("m/d/y", $tomorrow);
?>
Notice that we used one letter at a time with the function date to get the month, day and year. For
example the date("m") will return the month's number 01-12.
If we were to run our new script just after the 2010 Winter Olympics our display would look like:
Display:
Tomorrow is 02/28/10
Day:
d: Day of the month with leading zeroes. Values are 01 through 31.
j: Day of the month without leading zeroes. Values 1 through 31
D: Day of the week abbreviations. Sun through Sat
l: Day of the week. Values Sunday through Saturday
w: Day of the week without leading zeroes. Values 0 through 6.
z: Day of the year without leading zeroes. Values 0 through 365.
Year:
Other Formatting:
We suggest that you take a few minutes to create several timestamps using PHP's mktime function
and just try out all these different letters to get your feet wet with PHP's date function.
This tiny piece of code will register the user's session with the server, allow you to start saving user
information and assign a UID (unique identification number) for that user's session.
Storing a Session Variable
When you want to store user data in a session use the $_SESSION associative array. This is where you
both store and retrieve session data. In previous versions of PHP there were other ways to perform
this store operation, but it has been updated and this is the correct way to do it.
PHP Code:
<?php
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>
Display:
Pageviews = 1
In this example we learned how to store a variable to the session associative array $_SESSION and
also how to retrieve data from that same array.
PHP Sessions: Using PHP's isset Function
Now that you know can easily store and retrieve data from the $_SESSION array, we can now explore
some of the real functionality of sessions. When you create a variable and store it in a session, you
probably want to use it in the future. However, before you use a session variable it is necessary that
you check to see if it exists already!
This is where PHP's isset function comes in handy. isset is a function that takes any variable you want
to use and checks to see if it has been set. That is, it has already been assigned a value.
With our previous example, we can create a very simple pageview counter by using isset to check if
the pageview variable has already been created. If it has we can increment our counter. If it doesn't
exist we can create a pageview counter and set it to one. Here is the code to get this job done:
PHP Code:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
The first time you run this script on a freshly opened browser the if statement will fail because no
session variable views would have been stored yet. However, if you were to refresh the page the if
statement would be true and the counter would increment by one. Each time you reran this script you
would see an increase in view by one.
PHP Code:
<?php
session_start();
if(isset($_SESSION['cart']))
unset($_SESSION['cart']);
?>
You can also completely destroy the session entirely by calling the session_destroy function.
PHP Code:
<?php
session_start();
session_destroy();
?>
Destroy will reset your session, so don't call that function unless you are entirely comfortable losing all
your stored session data!
1. name: The name of your cookie. You will use this name to later retrieve your cookie, so don't
forget it!
2. value: The value that is stored in your cookie. Common values are username(string) and last
visit(date).
3. expiration: The date when the cookie will expire and be deleted. If you do not set this
expiration date, then it will be treated as a session cookie and be removed when the browser is
restarted.
In this example we will be creating a cookie that stores the user's last visit to measure how often
people return to visit our webpage. We want to ignore people that take longer than two months to
return to the site, so we will set the cookie's expiration date to two months in the future!
Don't worry if you can't follow the somewhat involved date calculations in this example. The important
part is that you know how to set a cookie, by specifying the three important arguments: name, value
and expiration date.
Retrieving Your Fresh Cookie
If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named $_COOKIE
associative array. The name of your stored cookie is the key and will let you retrieve your stored
cookie value!
PHP Code:
<?php
if(isset($_COOKIE['lastVisit']))
$visit = $_COOKIE['lastVisit'];
else
echo "You've got some stale cookies!";
This handy script first uses the isset function to be sure that our "lastVisit" cookie still exists on the
user's PC, if it does, then the user's last visit is displayed. If the user visited our site on February 28,
2008 it might look something like this:
Display:
Your last visit was - 11:48 - 02/28/08