Left Quote    Every day I get up and look through the Forbes list of the richest people in America. If I
- Robert Orben    
Right Quote
[login] | [Register]

Simple PHP Tutorial

by: Jester
Page: 1 of 9
(View All)

About PHP and ASP Style Tags

PHP stands for "PHP: Hypertext Preprocessor". Alot of people have been confused by this as the acronym PHP is part of the actual name derived from the acronym.

PHP is a general-purpose scripting language, its ease of use and learning curve make it especially suited to web development and the language can be embedded into HTML, making it relatively easy to produce brilliant, dynamic web pages.

PHP is open source, meaning anyone can download the actual source code and edit it, develop and refine it. PHP is growing at a rapid pace, why don't you give it a try?

For a programmer, PHP may seem very easy to get to grips with. For someone who has just mastered HTML and is looking to write a dynamic website, it may take a little more effort, i have done my best to write an easy-to-follow tutorial. Read onto the next section and get started.

Getting Started

One of the great features of PHP is that it can be embedded into HTML with ease. A PHP document doesn't have to contain PHP code. You could simply write HTML in the document and the server would handle it as HTML. The way you tell the server to invoke PHP to interpret PHP code and return the output to the user is with the PHP tags. Let's have a look.

PHP Mode Tags:

We open "PHP Mode" with the tag. So if we want to write a few lines of HTML code and don't want the trouble of using PHP to output it, we simply close PHP mode and write it as we would any normal HTML webpage. We can jump in and out of PHP mode whenever we want to.

Short Tags

If this feature is enabled in the PHP configuration, we can also use short-style tags to open and close PHP Mode:

This works in exactly the same way as above, it's just easier and shorter to type, a shortcut. Alot of people prefer to use the full tags as above, apparently short-style tags can cause problems when writing XML documents with PHP embedded, the server will become confused and parse code that isn't meant to be PHP code.

ASP-style tags

We can also use ASP-style tags to open and close PHP mode, if this feature is enabled in the PHP configuration file.

This method is rarely used, but it's there if you prefer it.

A Practical Use

If you're new to this, you may be thinking "What the hell is PHP Mode?", let's have a look at a simple HTML document with PHP code embedded into it.

Now as you can see, if we don't open the PHP mode tags, we can just write out the HTML as normal, when we do open into PHP mode we must use only PHP commands, otherwise the server will return a "parsing error". As with Perl almost all lines in PHP end with a semi-colon (;). Remember, your PHP pages will be parsed alot more quickly if you only go into PHP mode when it is necessary. In the above example we use the echo() function, this function is the same as print() in Perl. It just prints out the string between the quotes. not very useful in the above case, but it gives you an idea of the structure of a PHP document. Let's go on and look at variables.

Variables, Comments

We can assign values to variables with ease.

Assigning a value to a variable works from right to left. The value on the right will be assigned to the variable name on the left. Let's look at each one:

$variable = 10; - This simply assigns the value of 10 to the variable name $variable. If we now printed out the variable, it would return 10. If we used the variable in a function it would be handled as the value 10. Assigning 10 to a variable is just a way to give 10 a name for us to work with.

$variable = 'This is a variable'; - This assigns a string to the variable. This variable would now be equal to This is a variable. It allows us to easily work with the string, using a variable to represent it.

$variable_two = "$variable containing a variable"; - notice i used double quotes to contain the string this time. I did this because we want to assign the value of $variable to $variable_two. This will interpret the value of $variable and assign it, with the other parts of the string, to $variable_two. $variable_two would now contain "This is a variable containing a variable". If i were to use single quotes:

$variable_two = '$variable containing a variable.';

$variable_two would contain "$variable containing a variable". This is called interpolation. If you wish the value of a variable to be interpreted, it must be contained within double quotes, if it isn't, PHP will not interpret it and will use the actual string within the quotes.

$variable_three = $variable_two; - We can assign a variable to another variable easily. We do not need to contain it within any quotes. $variable_three will now be a copy of $variable_two. Referring to interpolation, what would happen if we did:

The first example would be the same as without quotes, they both work the same; it is just good coding practice to leave out the quotes if they're not necessary. The second example would not interpret the variable value and $variable_three would contain simply "$variable_two". Get to grips with interpolation.


Look in the example above:

What's the deal with that // or bit? That's a comment. You can leave little notes in your PHP coding, explain what is happening so others can understand your coding more easily. One line comments are of the format:

// This is a comment

Anything after // and on the same line, will not be parsed by PHP, PHP will know it is a comment and not interpret it as a PHP command. We can also use:

/*This is a comment
that can span multiple lines*/

This comment can span multiple lines, /* signifies the start of the comment, */ signifies the end of the comment. Any text between these two symbols will not be parsed by PHP.

We can also use Perl-style comments:

# This is a comment
This can only be on one line also.

Another PHP Example

Now that we know how to use variables, let's write a page that uses them.

Firstly we open PHP mode and assign our variables their values. We then close PHP mode and print out the HTML. When we get to the title, we open PHP mode, echo the title variable, which contains "Hello World" and then close PHP mode. We then print out more HTML, open PHP mode and echo the string containing my name, close PHP mode and print out the rest of the HTML. Easy eh?

A shortcut

In the above example, when we want to print out a variable name we do <?php echo $title; ?> . There is a shortcut for this, PHP is clever that way.

<?=$name?> is just a short way to do <?php echo $name; ?> . Remember the equal (=) sign, it's alot easier to use this method when printing out many variable values.


If you're a Perl lover trying to learn PHP, you may be surprised with how it behaves. If you submit a form containing:

<input type="text" name="username">

The data submitted through this form input will automatically be available to you in the variable $username. If you set a cooke named "a_cookie", this will be automatically available to you in $a_cookie. If you send the query string:

The variable $section will be available to you automatically, and will contain "mail". This is a nifty feature of PHP, but some people question it security-wise. You can turn "register global variables" off in the PHP configuration file if you wish, to increase security. If you do:

But don't worry about that yet. Just thought I'd mention it.

That just about wraps it up for variables, let's go on and look at arrays.

Arrays, Multi-Dimensional Arrays

When i first started learning PHP arrays confused me. I learned Perl first; arrays and variables in Perl are represented with different symbols. Not so in PHP, an array looks exactly the same as a variable, it starts with the dollar ($) sign.

$array = array('cat', 'dog', 'fish', 'rabbit');

Think of an array as a variable that can store many separate values. We can access each item in the array.

Now each item of the array is accessed using the variable name, followed directly by square brackets containing the number of the item to be accessed. The number listing of the array starts at zero, so the first item is 0, second is 1, third is 2, etc.


Let's have a look a little deeper into arrays. Arrays have a "key" and a "value". The key is what you use to access the value.

See how each number(key) has an association with it's value? The "keys" don't have to be numbers. If the keys aren't defined, they will default to integers to represent each array item. Let's define another array.

,br> Now we can use the key associated with it's value to return the values:

This works like associative arrays in Perl, the methods are almost identical. Arrays don't stop here, they can become very complex, especially when we get into multi-dimensional arrays.

Multi-dimensional Arrays

We can define more complex arrays like so:

The above is a two-dimensional array, it has two "levels" to it. It has three arrays stored within one array. You can access each array within the array by using the KEY associated with a deeper array. You can then use the keys within the deeper arrays to access the array values.

As you can see, arrays can become very complex, you could define three, four, five-dimensional arrays.

Ok, I think that about does it for arrays, let's go on to conditionals.

Conditionals, if/else, Elseif

We can perform actions in PHP based on whether or not a conditional statement is true. Let's take a look at an example.

Look at it logically: "If two is greater than one". The > operator means "greater than". The conditional statement is contained with the brackets following the if() function. If this statement is true, the PHP code between the curly braces, { } will be executed. Two will always have a greater value than one, so this statement will always be true.

Now here we say "If one is greater than two, print out so. Or ELSE, print out "one is not greater than two".


There are many operators you can use in PHP, and some come in handy for conditionals.

We can use these operators in our conditional statements. If a statement is TRUE, the if() function will execute the functions contained within the curly braces, if it is NOT true, it wont. We can optionally include an else statement after the if statement. But it doesn't stop there.


Take a look at the code below and see if you can figure out what's happening.

PHP will test if each condition is true, if one is, it will execute the code between that statements curly braces. If none of them are true it will execute the code contained within the else statement. Remember the else statement is optional, if we don't want anything to happen if no conditions are true, we can simply leave this out.

Logic: If $number is greater than 10, print out so. ELSE if $number is less than 5, print out so. ELSE if $number is greater than 5, print out so. ELSE print out the code between the else {} curly braces.

So what will actually happen here? Well none of the statement are true, 5 is not greater than 10, or less that 5, or greater than 5. The else statement will be executed. Let's use some strings:

Not too difficult, I'm sure you'll agree. Conditional statements are essential, as you'll find out if you decide to use PHP.

Embedded Example:

I'm assuming, if you're reading this you're familiar with HTML, so let's put the above to a practical use. Let's ask the user for their name:

PHP is case sensitive, i.e Bill is not the same as bill, Bob is not the same as bob.

Take your time and look through the above script. Notice we can jump in and out of PHP mode whenever we like, even within a conditional statement's curly braces, print out the HTML we want to, and then open PHP mode again and close the conditional's curly braces, then proceed with the next conditional:

If we didn't jump out of PHP mode, we would have to do:

If an echo statement that uses double quotes contains double quotes within it, we must "escape" them using the special "" escaping character. Personally, i find this very annoying to type out, especially when outputting alot of HTML, it's much easier to close PHP mode and type out the HTML as normal, using the <?=$variable?> shortcut to output any PHP variables.

All the script does is check if $name has been entered, if it hasn't, it displays a form asking them to enter their name. If $name has been entered it executes the if, elseif, else statements contained within the else statement. If the name is Bill it tells him he is the author, else if the name is Bob it tells him he is a member, or else it tells the person they are a visitor.

I think that's enough on conditionals, go on to control structures.

Control Structures

For those of you who know Perl, you will see that PHP has borrowed alot from Perl. Infact the first PHP interpreter was written using Perl, the syntax is very similar in alot of ways.


The foreach function is for use with arrays. It allows you to go through each item in an array.

Go through each value in $fruits and call it $fruit. The above code would output:


The first parameter in the foreach() function tells PHP which array to go through. The second parameter tells PHP which variable to assign the value to as it goes through them. So as foreach() handles the first array item, $fruit contains "apple". As foreach() handles the second array item, $fruit contains "pear". This repeats until each item in the array has been processed.

Foreach is a very useful control structure. In the above script, if, on its travels, foreach finds an array value that is equal to "apple" the if statement is true and it will print out that the array contains "apple". It will go through each array item and check if the conditional statement is true.


the while() function has the syntax:

while(condition) {
// PHP code here

This function does exactly what it says. WHILE the condition is true it will execute the PHP code contained within the curly braces.

WHILE 1 is equal to 1, print out "1 is equal to 1, duh!". 1 will always be equal to 1, so this while() function would loop through over and over, forever. The while() function will execute until the condition within the brackets is false.

Will output:

loop finished

The while() function checks "is the value stored in $number less than 10?" it contains 0, so it is less than 10. The statements between the curly braces are then executed. We print out the value stored in $number and then increment it (add one to it). $number is now 1, the function checks is it still less that 10? Yes, it prints it out and increments it again, this repeats until the value stored in $number is no longer less than ten. When $number is equal to nine, it is printed out and then incremented to ten, it is then no longer less than 10, the loop exits and the script continues.


We could also get the same results as above using the for() function. Here is the format:

for(intialise; condition; action) {
// PHP code

Firstly we intialise, then we enter under which condition to execute the for loop, then we define an action to be executed each time we go through the loop.

for($number = 0; $number < 10; $number++) { echo "$numbern"; } echo 'loop finished';

This would output:

loop finished

$number = 0; - Firstly we intialise the variable $number with a value of 0.

$number < 10; - Then we tell the for function to keep executing the code in the curly braces until the conditional statement $number < 10 is no longer true.

$number++ - Lastly we define the action, in this case we tell the for function to increment $number each time it goes through a loop.

Thus we get the results above, set $number to zero. While $number is less than 10, execute the code in the curly braces, at the start of each loop add 1 to $number. This results in the for function printing out the value stored in $number then looping through and adding 1 to $number until $number is not less than 10, then the loop exits and the script continues.

Handling Files

We can use PHP to open files and manipulate the data contained within them.

Opening a File

To open a file or a URL we use fopen().

The fopen() function normally uses two parameters. The first is the file which we want to open. This can be a file on your system, or a file on a remote server. In this example we are opening a text file on a windows machine. The second parameter is the "mode". We can open a file for only reading. We can open a file for only writing. We can open a file for reading and writing. In the above example "r" means reading.

Reading Info from a File

After we have opened the file, we will probably want to do something with it. To read the contents of a file into a variable we use fread().

Now fread() also uses two parameters. The first parameter is the variable to which we assigned the fopen() function, the second is the number of bytes we want to read up to in the file. In this case we want to read the entire file, so we use the filesize() function to get the size of the file specified in the $filename variable. Thus, it reads the entire file in.

Let us assume C:file.txt contains:


So now $contents would contain:

$contents = "line1nline2nline3nline4nline5";

If we printed the variable out the output would be:


The contents of the file are read into a string, complete with newline characters (n). We can then process this string however we like.

Writing To a File

We can also write data into a file once we have opened it. To do this we use the fputs() function.

Firstly we open the file. Notice the "a" parameter? That means "open the file for writing only, and place the file pointer at the end of the file". So now PHP opens myfile.txt for writing and positions the file pointer at the end of the line.

We then use fputs() to write to the file. We define our string in $string which i put "nline6". The n bit means start a new line, and the print out "line 6". We then close the file.

So now what will the file contain?


I think you'll agree they've made it very easy to handle files in PHP.


There are various modes you can use to open a file, they are listed on the fopen() function page, but I'll stick them up on here too

'r' - Open for reading only; place the file pointer at the beginning of the file.

'r+' - Open for reading and writing; place the file pointer at the beginning of the file.

'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

The above was taken from's fopen() function reference page.

Include() and Require()

Two very useful functions in PHP are include() and require(). These functions do what they say. They allow you to include other files into a PHP document. Require() and Include() behave slightly differently, but are basically the same.

Let's write out an example of how we could use include():


This will be the header of your page.


This will be the footer of your page.

Now we have two files containing some HTML and some PHP code. If we're making many pages, why do this in every file? We could just include these two files into each page, making documents smaller and simpler. This is how we would do it:


This would simply include page_header.php at the top of the file, and page_footer.php at the bottom of the file. We wouldn't need to write out the code every time, just include it. An included file can itself contain an include() function, and PHP will handle it with ease. Always try to use the full system path to the file you're including, not the relative path, this will ensure PHP can find the files easily. In the above example we simply include the header and footer PHP documents and print out a few variables. We also use the foreach() function to go through each value in the $members array and print the members out in a neat little table.

In the above example we could use require() and it would have the same effect, so what's the difference between them?

What's the Difference?

One difference between require() and include() is the way they handle an error. If PHP cannot find the file you have entered in the include() function, it just prints out a warning and informs you that the file was not included, yet the script continues. If the same happens with require(), it doesn't issue a warning, it causes a fatal error meaning that if the require function doesn't return true, PHP will stop executing the script there and then and tell you why.

As it says on the PHP reference page: "In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless."

Cookies and PHP, Mail()

Another great feature in PHP is cookie handling, PHP lets us do this with ease. The function we use to set a cooke is setcookie().

setcookie('username', $name);

It's as easy as that, the first parameter is the string name of the cookie, this cookie will now be know as username. The second value is the value which you want to store in the cookie, in this case it's a variable $name. The above is the bear minimum, this is the simplest cookie you can set, and this cookie will deleted when the user ends their session (closes their browser). We can define how long we wish a cookie to last:

It's as easy as that. Another function on PHP is time(). This simply returns the current UNIX timestamp, so we call this, and then add 31536000 seconds to it. What is 31536000 seconds? That's right, a year, so this cookie will last for one whole year. That is if the client doesn't delete it or something, anyways, the third parameter is the life of the cookie, how long we want it to last, if this is left undeclared the cookie is deleted when the user's session ends. If we wish to delete a user's cookie we can simply set the life to a time in the past, e.g.: time() - 3600. That will set the user's cookie life to one hour in the past, deleting it. Remember, cookies must be deleted with the same parameters they were set with.

We can also use a forth parameter, the fourth parameter is the cookie path.

The fourth parameter defines a path from which the cookie can be accessed. In the above example only scripts inside /jesteruk/folder/ will be able to access the cookie ($username), in scripts outside this folder the cookie will be unavailable.

Yup, there's a fifth parameter, the fifth parameter defines a hostname that can retrieve the cookie.

The fifth parameter is the domain which can retrieve this cookie. Normally a cookie can only be accessed by the domain that set it, otherwise sites would be able to get private information from cookies set by other sites. With this parameter we can define another domain which can retrieve the cookie we are setting.

Retrieving the Cookie

Once you have set a cookie on a user's system, it is only available when they load the next page. The cookie can be accessed very easily:

When the cookie is set the value is automatically URL encoded, when the script retrieves a cookie, it automatically decodes the value, so you don't have to worry about that.

Always remember, a limitation of cookies is that you have to set it before you can send the HTTP headers. In other words, always do all your cookie setting BEFORE you output any HTML, otherwise the cookie will not be set and your page will have an ugly error stuck on it.


Another thing made easy in PHP is sending mail. We use the mail() function.

Simple eh? The first parameter is the address to which the email is destined. The second is the subject of the email. The third parameter is the actual message. This is the minimal use of this function. By using a fourth parameter we can add additional headers to our email.

This allows us to define raw headers to be sent with the E-Mail, such as an address for the receiver to reply to, an address so the receiver can see who the E-Mail was from. The headers should be separated with rn

Sending mail in this way makes it very easy, we don't have to actually "talk" to the sendmail program as we would if we were using Perl, although this can still be done is desired. We can use string building techniques to build an E-Mail message:

By using the .= operator we're telling PHP to append the text in the quotes onto the end of the data already stored in $message, allowing us to build up a formatted message. We can also send HTML E-Mail:

The Content-type header allows us to send the E-Mail as HTML, so we can include tables and format the E-Mail as we would a HTML page. The default is plain text, so if you want to send it as HTML you have to include the header.


As with any decent language, PHP allows you to write your own functions. Let's look at a simple one.

As you can see the name of the function fits. We declare a function by typing, of all things "function", followed by a space, and then the name of the function followed by two brackets, you may have noticed this by now, all functions have these two brackets, for passing parameters. In this case we aren't using any. Then we put the code we want to execute between the two curly braces, this is a function. To call this function we would just call it's name.


Which would print out "This function prints a string". It executes the code between the curly braces. A function can contain any valid PHP code, even other functions. This may seem pointless, but read on, allow me to elaborate.


Whether you call them parameters or arguments, they're the same thing. A parameter is a value that you can pass to a function and use inside the function. Let's write an example.

Now when we call this function, we can include a parameter, the value included as a parameter will then be handled, within the function, as $text, so say we do:

The contents in $string will then be passed to the function, where they will be handled as $text. In this case we just print it out. We could use two parameters:

In the above example, if you then tried to work with the variable $sum outside of the function you'd get a shock. The variable $sum does not exist outside of the function. We can change this:

We do this by making the variable $sum a "global" variable. To do this we simply state global $sum;. Now $sum is accessible from anywhere in the script, it's not just a variable private within the function. If we didn't define this variable as global, when we tried to print it out after the function call, it wouldn't work.

A function is useful when we want to perform the same actions over and over again. Let us imagine we have written a script that allows a user to post a message on a "guestbook". Yet we don't want to allow them to use HTML in their post, in their name, or in the subject of their post.

Now this function will take our argument, if it contains any HTML (anything surrounded by < and > , it will take it out of the string. The return $stripee; at the bottom of the function tells the function to return the new value of $stripee to us.

Now we don't want any HTML in the user's posts, maybe we don't trust them, we don't want them to be able to mess around with our page's HTML, so we use the function we have written to clean up:

Send each variable to the function as a parameter, let the function clean out any HTML, and then return the new value of the string to the same variable name. So now any HTML would be gone:

Using functions makes things alot easier, you can put all your functions in a separate file and just include() them into your script.

Conclusion, Resources

In this tutorial, I tried to cover some key aspects of PHP to help kick-start anyone wishing to learn. You can't learn by just reading, you have to go and write a script, just jump in and do it; learn some common functions, learn the syntax, after you've typed it out a few times it sticks.

PHP is growing everyday, and with each new version come new functions, new features, no one can know it all, and no one can write a tutorial that covers everything, this is just a basic PHP tutorial to try and help you get started.

I plan to write more PHP tutorials that focus on particular aspects of PHP, such as PHP with databases, when you read this maybe I will have got off my arse and written them. Please feel free to leave any comments, if I made any mistakes anywhere, I'll be glad to hear about them.

You may also want to have a look at a Perl Tutorial, which will spell out some rules you should follow when writing code. Perl is very similar to PHP, and the same rules apply when writing PHP code. Remember, a subroutine is Perl's way of defining functions, so the rules stated for subroutines apply to functions in PHP.


  • - The official PHP homepage, huge archive of PHP function reference, help, tutorials, all you need.
  • - Get help if you're having problems.
  • PHP Builder - A PHP community site, featuring how-tos, tutorials, and discussion forums.
  • PHP Resources - A site where PHP programmers submit scripts they have written. If you want a PHP script, this is the place.

1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  
Next »

No Comments for this page.

You Must be logged in or a member to comment.

Tutorial Stats

Tutorial Stats

1 Total Comments
3.25 Rating of 5 (4 Votes)


Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article



· One File Website
· Pagination with PHP
· Building a Comments Script
· Complete Members System
· Variable Scope

"" Copyright © 2002-2019; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank