IntroductionThis tutorial was written to introduce you to PHP, it assumes you know nothing about programming at all, starts with the very basics and slowly guides you through some of the concepts of PHP programming. Hopefully this tutorial will clear up the basics and allow you upside-down people to follow, and I quote, some of my other “too technical” tutorials.
PHP?PHP is an ever-popular web scripting engine. It allows you to create dynamic web pages easily and quickly. It has a very rapid learning curve so once you get the basics down you’ll progress very quickly and start writing some nifty scripts. In newbie terms: it’s a thingy that runs in conjunction with a web server that easily allows you to create web pages that change—such as guestbooks, list users’ comments, discussion boards, top fifty lists, administration panels … and so forth.
Yeah ok, so how do I use it?Firstly you must ensure you have access to a web server that is compiled or set up to work in conjunction with PHP. Most good web hosts these days will offer PHP support, and if they don’t you can always bombard them with e-mails and whine until they do. PHP is getting very popular so the chances are you’ll have access to it. If you don’t you can always install it yourself on your own system, along with a web server. You can find instructions on how to do this, on a wide range of operating systems, in the PHP Manual.
So How Do I write It?PHP is very simple to use, the first thing to note is that PHP is embedded into HTML. You don’t have to have pure PHP code in a PHP document, you can switch between HTML and PHP, let’s take a look:
Simple, eh? Let’s have a closer look at it. The script starts off as any HTML document would, with a DOCTYPE definition followed by an open HTML tag, title, body tag, the only bit we’re interested in is the stuff between <?php and ?>. That is the PHP code, only when you open the PHP tag, <?php, can PHP code be used.
This is a great feature of PHP as you can just type out HTML if that’s all you need and jump into “PHP Mode” when and if you need it, remember: a PHP document doesn’t have to contain only PHP.
So What Happens?Remember how I said you need a web server that works in conjunction with PHP? You need this because the PHP code has to be executed, the PHP interpreter handles this. The web server is set up to recognize certain extensions as a PHP document, say .php. here’s what happens:-
That make sense? PHP code does not have to be compiled (converted to an executable program) before hand, when the web server passes PHP the document, it is then compiled on-the-fly (or interpreted), executed, checked for errors and then returned to the web server. So what is sent to the client (the person requesting the document) is not PHP code at all, it is the output of the PHP code. So … what would they receive from the above program?
All the PHP code did was to output
EchoThe only bit of the above script we’re interested in is this:-
We opened into PHP Mode, used the echo function (language construct, whatever) to output a sentence, or string. Echo is just for printing stuff out, for example:-
Would output the text “Hello World!”, just type <code>echo 'whatever'; </code>, the string is enclosed in single quotes and after the closing quote is a semi colon (;). We then closed PHP Mode and wrote out the end of the HTML document.
The PointWell in the above script there really is no point, many a time I have been asked something similar to:
“Why not just print out the
“Because this is an example showing you how you go into PHP Mode, how the web server handles the request and what goes on in the background, not a discussion forum, you silly person.”, I answer.
Points To Remember
Now that we have that cleared up and you (hopefully) know how PHP works, how to embed it into HTML, (hopefully) have access to a web host that uses it and didn’t fall asleep on your keyboard and are now ready to get coding some PHP. Click “Variables” and learn how to use variables in your PHP documents.
Got past the opening page, eh? In this section of the tutorial we’ll learn how to use variables in our PHP scripts and, most importantly of all, why we use them.
VariablesUsing variables in your PHP documents is very easy, this is how variables look:
A variable starts with a dollar sign ($) followed by whatever you want to call it, variable names can consist of letters, numbers and the _ character. However, do not start variable names with a number.
What Do They Do?Variables store a value, whether it be a sentence (string), number (integer) or a letter (char). You assign a value to the variable using the assignment operator (=).
We just assigned the value of 1 to the variable $variable. This $variable is now 1, so if we printed it out, it would print 1.
We can assign a variable a number, a letter or a sentence.
If we then used echo to print out these variables, the output would be whatever the variable contains. Variables are essential and you must learn how to use them, let’s take a look at the semantics of using the echo statement with variables.
Echo and VariablesUp to now we have only used the echo statement with a string and with a single variable. How you use the echo statement, or more specifically if you use single quotes, double quotes or no quotes at all depends on what you are printing out.
Single QuotesWe use single quotes when we want to print out a something that contains no variables (or arrays, we’ll get to them next, ignore for now), take a look:
That works fine, it will print out the string.
No QuotesIf we are printing out a variable, and nothing but a variable, we don’t need to surround it by quotes at all, take a look:
Double QuotesWhat if we want to print out a variable within a string or something? Then we use double quotes, take a look:
If a variable is to be printed out amongst the words of a string then the whole thing must be contained within double quotes. If we wish to interpolate a variable into a sentence this is how we do it. Why, though? What if we used single quotes?
Not what we want, is it? We want the value of the variable to be printed, not the name along with the dollar sign, this is the difference between single quotes and double quotes. Use single quotes when just echoing out a normal string, if it contains a variable, use double quotes.
This applies not only to echo, but with everything in PHP, when assigning a variable to another variable we use the same rules.
$myname would contain
That’d work as we want, remember that, use quotes only if you need them, and use the correct ones.
An AlternativeAnother method we can use when wanting to print out a variable is jumping out of the quotes, take a look:
The latter of the two examples may not make grammatical sense but it shows you how you use the periods to attach the variable into the string. Close the quotes, type a dot, type the variable and then, if you need to, you can type another dot and open the quotes again. Have a play around with variables, echo and assignments, you’ll see what I’m talking about.
It wasn’t really necessary to show that last method, but if I didn’t I probably would have gotten a comment at the bottom by some PHP “guru”:
<sneer>This tutorial sucks, you didn’t even mention the dot thing, hahaha call yourself a PHP coder? Stop polluting my screen with this crap!</sneer>
Indeed. So there you have it.
But, why?Well … the reason we used variables in the above examples is still unclear. Why not just write “My name is Jester”? Well what if we wanted to use the value “Jester” through out a script many times? We could just type “Jester” in every place we wanted to use it. What if I changed my name, though? I’d have to go through and change every instance of “Jester” to my new name, if I had it stored in a variable I could just assign the variable a new value and it’d take effect in every instance I used it. This is the power of using variables.
Another point is, what if a user submits the value of “10” to a script? You can’t just store “10” on its own in a program, can you? You need to put it somewhere, and what better place than a variable?
Still unclear? Don’t worry about it, at this point in my PHP lessons I was very hazy too. You got this far, keep reading and you’ll see why we use them. Let’s go on and look at Arrays.
In this section we’ll look at arrays, how we use them, why we use them and we’ll take a look at a few special arrays available to you in PHP scripts.
ArraysArrays in PHP are just what they say, arrays of variables. Let’s take a look at what one would look like.
An array is accessed by the name of the array, followed by square brackets containing the key of the array item we want to access.
An array contains an array of values, each of which are referenced by this “key”. We use the keys to access each individual item within the array. We would assign an array like this:
All that information would be stuck into the $array array. We could then access each item:
The key index consists of numbers, the first value in the array is accessed with 0, NOT 1. The second accessed by 1, the third by 2, and so forth.
Associative ArraysYou don’t have to access array items with number values starting at 0, you can define your own keys.
That may look a bit daunting, but just look at it. Each array key => item is defined separated by commas. The part before the => is the key and the part after it is the value associated with that key.
Associative arrays allow you to associate different words with each array item, it is easier to remember which word accesses what item in large array, your mind rememebrs words easier than having to count, starting from zero, in your head.
Remember the single quotes/double quotes thing? This applies when accessing array items with keys also. An integer value or a variable needs not be quoted, a string value needs aingle quotes, a string value containing a variable needs double quotes.
$_SERVERThis array contains lots of values for you to use in your scripts. It contains the client’s IP address, the browser version, the URI of the script being access, various HTTP headers and much more, here are some examples.
$_POSTThis array contains anything that has been submitted through the POST method. We will be looking at this in the next chapter.
$_GETThis array contains anything that has been submitted through the GET method. We will be looking at this in the next chapter.
$_COOKIEContains cookie information for the client. Say you set a cookie on their machine named “mycookie” with a value of “Jester”.
$_REQUESTThis associative array consists of everything in $_POST, $_GET, $_COOKIE and $_FILE.
For more information see The PHP Manual.
In the next chapter we’ll discuss using forms with PHP scripts and how we process the information submitted.
In this chapter we’ll cover using forms with PHP. How we retrieve the information submitted through a form (both GET and POST methods) and I’ll also introduce you to multi-dimensional arrays and how we can submit an array through a form.
Forms and PHPI briefly mentioned the $_POST and $_GET arrays in the last chapter, in this chapter we’ll see what they’re used for. We can submit a form to a PHP script, let’s take a look at a simple form.
That HTML code would create a “form” on your page. The form has two input boxes named “firstname” and “lastname”. Also, look in the
Let’s assume the user entered “Joe” as their first name and “Blogs” as their last name.
If you use the POST form method then all the inputs’ values will be within an associative array,
GETWhat if we submitted the form with the GET method? I’m sure most of you have already figured this out by now, but we’ll go over the example anyway.
All we did was change the form “method” to “get”.
If we submit a form through the GET method then we use the $_GET array rather than the $_POST array.
More on $_GETThe $_GET array is not only useful with forms. Try using the GET form above, when you submit the form look up in your browser’s address bar. You will see something similar to (assuming you are Joe Blogs):
The GET form method just sticks everything in the browser address bar, everything after the ? has a name: the Query String.
What I’m trying to get at is we don’t only use the
Submitting the query string and hence making the variables in it available in the
Look at everything after the
Have a play around with these arrays, get used to using them.
Remember how we defined an array?
Which we can then access like:
Well instead of just having one value associated with a specific array key, we can actualy assign an array, within an array. So “value1” could actually be an array in itself—creating multi-dimensional arrays. Let’s take a look.
That may look a little daunting, but all we did was instead of giving an integer, char or string for an array value, we used another array, so how can we access the items in this array?
That’s how you use multi-dimensional arrays. All it is, is an array that has keys that reference other arrays. Why did I show you this? It is possible to submit form inputs as arrays, so instead of
Submitting Arrays Through FormsLet’s look at the HTML, how do we make PHP know that the form input submitted is to be an array?
All we do is, after the input name (in this case “checkboxes”, follow it with two square brackets. So the name of our inputs that will all be stored in an array wthin the
That’s easy enough, now let’s look at how we’d get at these values, it’s the same as in the above example.
This is the first time we have seen a real function used. We used the count function, all it does is count how many values are present in an array. As we submit our “checkboxes” input as an array, if they check one box
If this lost you, don’t worry about it, just try to get variables and simple arrays down. That’s all you really need when you start off, I just showed you this because no one mentioned it to me, I had to figure it out for myself.
That about clears up using forms with PHP, remember, if you have any questions just drop me a message, or comment at the bottom. In the next chapter, now that you have seen a function and it’s probbaly making you think “I need to know more about those”, we’ll go onto learn about functions and how we use them.
In this chapter we’ll cover functions with PHP. How to use them, where to look them up and how you can define your own.
FunctionsFunctions are what you use to make PHP manipulate and process data, or just do a big bunch of statements quickly and easily without having to type the same lines of code over and over. PHP has hundreds of available functions for you to use and there’s normally always one you can use for what you want to do. On the rare occasion there isn’t, you can just write your own.
Firstly, let’s look at how we use existing functions.
Look at the example, we used the strip_tags() function. What this function does is strip any HTML or PHP tags out of a string. Look:
The tags are gone. The function stripped them out and then returned a new version of the string, with no tags, back into the variable that we specified (
So the function strips the tags off the value that we pass to it, then we assign the new value from the function to
PHP has many built-in functions like the one above. You can search on PHP.net’s function list to find them (see form at top of page). It’s really down to memory, the more you get into PHP the more functions you’ll use and remember.
_“I see and I forget, I hear and I remember, I do and I understand.”—Confucious_
This applies to programming, too. Sit here reading and you’ll forget it, open up a text editor, write a program, test it, debug it and change it, play around with PHP and you will remember.
Parameters/ArgumentsFirstly parameter and argument is the same thing. Just some people call them parameters, some call them arguments. In the above example we passed one parameter to the function strip_tags. Functions aren’t limited to accepting one parameter, they can accept a number of parameters. Some functions require more than one parameter, some only have one, some require a certain amount of parameters or one parameter and have extra, optional parameters. strip_tags has an optional parameter that you can take advantage of. Let’s take a look.
Look, we passed an extra parameter to the function. The second parameter is a string (hence why it is surrounded by quotes) containing any tags we don’t want stripped from the string. We passed the function only one tag, the paragraph tag, so any paragraph tags in that string will not be stripped, but all other tags will. So the string returned from the function would be the string we submitted, minus any HTML or PHP tags, except for paragraph tags.
Okay now we know about parameters and how we call and use functions, let’s look at how we can write some of our own.
Custom FunctionsPHP allows us to define our own functions, let’s look at a very simple one, just to see the format.
Easy eh? We just write “function”, followed by the function name, followed by two brackets. We then open a curly bracket to start the function statements. It is ended by the closing of the curly brackets. We could now use this function in our script.
Doing that would call our function and run the statements inside it. That’s a pointless function, but it shows you how to define one. We could pass a parameter.
With that function we passed a parameter. So now we could do:
Passing the string
Returning a ValueTo make our function return a value is simple, this is how we do it.
We just do whatever we want to do, and then return
Note: in this function we used two new functions: substr() and strtoupper(). Click on the links to go to the PHP reference pages and see what these functions do. This is how you’ll learn functions if you’re going to get into PHP, so go read it.
So now we could do:
Our function returned the string which we then assigned to a variable. We could then pass this variable to other functions if we wanted, do whatever we want with it before we print it out. Have a play around with functions and get used to them. Before we move on, one more thing….
Getting GLOBALSometimes in functions you have to use global. Let’s look at some examples to show you why.
See how we use $thestring within the function? Well if we then, outside the function, typed
There’s two main reasons why we’d need this:
Here’s how we make a variable global.
What we did above was make a variable named $length which we wanted to be usable within the function too. The line that does it is
That’s about it on functions, in the next chapter we will look at an important part of your learning: Control Structures.
This chapter is an important one, we will covers control stuctures. Control structures allow us to control our scripts, to perform different statements, output different output depnding on certain conditions, to perform loops and so forth. Here we’ll have a look at a couple of them.
ConditionalsConditionals allow us to perform different statements depending on certain conditions, here is the formal for a simple if statement.
It kind of speaks for itself. The
This allows us to print out something if the condition is NOT true also. So if it is true it will execute whatever is between the curly braces for the if() statement. Or else it will execute whatever is between the curly braces for the else statement. There’s more, we can use
This time we used the == operator. If $a is EQUAL to $b, do whatever is in the curly brackets, ELSE IF $a is greater than $b, do whatever is in those curly brackets, OR ELSE do whatever is in the final curly brackets.
Conditionals are very useful and it is essential you know how to use them, have a play around.
WhileWhile is a function that allows us to perform actions
This process repeats until
While is a very useful control structure, if you get deeper into PHP and start working with databases and text files you will use it a lot. Have a play around with it.
Putting a condition inside the () after the while statement that will always be true (like 1==1) is not a good idea. It will produce an inifite loop.
MoreThe two control structures I have showed you are the most commonly used. There are more but I don’t want this chapter to be too long. So rather than repeating what is already out there available to you, I’ll just direct you to The PHP Manual: Control Structures. There you will find information on all the control structures and exhaustive directions on how to use each of them.
Go on to the next chapter to learn how to get deeper into PHP.
This Introduction to PHP is just about wrapped up. Now it’s up to you to go on and learn more about the language. There is heaps of documentation out there for you to read, install PHP on your system, or if you have a host that supports it use that, and get reading and doing.
And remember, have a question about this tutorial? Want to see something else added to to or want me to show you how to do something? Leave a comment below or send me a message.
No Comments for this page.