Search
Left Quote    I find that the harder I work, the more luck I seem to have.
- Thomas Jefferson    
Right Quote
 
[login] | [Register]
 

Introduction to PHP

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

Introduction

This 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:-
  1. Internet browser requests “index.php” from “www.allsyntax.com”.
  2. AllSyntax web server receives request.
  3. Web server checks “what type of document is this?”, oh look ”.php”, it’s a PHP document.
  4. Web server invokes the PHP engine and passes it the contents of “index.php”.
  5. PHP Engine checks the document and anything between <?php and ?> is converted to HTML output.
  6. PHP returns the HTML output to the web server.
  7. Web server sends document to internet browser.

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 "<p>This is my first PHP script.</p>", when PHP sends the output from the script back to the web server the above is what remains. If a user views the source of a PHP page in a text editor they will not see PHP code, all they will see is the output of that code.


Echo

The 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 Point

Well 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 '<p>This is my first PHP script.</p>' using normal HTML!?!?”.

“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

  1. You need a web server that is working in conjunction with PHP, don’t know if yours is? Ask your host “can I use PHP?”. They said “Nope”? Tell them how much they suck and then install it yourself .
  2. A PHP document doesn’t have to contain only PHP, PHP is embedded into HTML.
  3. PHP code is contained between <?php and ?>
  4. The above script was just an example, an example!

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.

Variables

Using 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 Variables

Up 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 Quotes

We 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 Quotes

If 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:


    Note:
this is also valid if you are just echoing or assigning a number value, and only a number value.

Double Quotes

What 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?



My name is $variable

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 "My name is $variable", if we wanted to assign the value of the variable to $myname we’d use double quotes:



That’d work as we want, remember that, use quotes only if you need them, and use the correct ones.

An Alternative

Another method we can use when wanting to print out a variable is jumping out of the quotes, take a look:



And again:



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.

Arrays

Arrays 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.

$array[key]

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 Arrays

You 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.

Special Arrays

$_SERVER

This 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.



$_POST

This array contains anything that has been submitted through the POST method. We will be looking at this in the next chapter.

$_GET

This array contains anything that has been submitted through the GET method. We will be looking at this in the next chapter.

$_COOKIE

Contains cookie information for the client. Say you set a cookie on their machine named “mycookie” with a value of “Jester”. $_COOKIE['mycookie'] would contain 'Jester'.

$_REQUEST

This 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 PHP

I 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 <form> tag, the “action” points to “myscript.php” and the “method” is “post”. Meaning the form will be submitted to “myscript.php” using the HTTP request-method POST. So how could we get the information that has been submitted to our script?

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, $_POST. If you submit an input named “name” it will be available in $_POST['name'].

GET

What 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 $_GET

The $_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 $_GET array when using forms, we could simply do this:



Submitting the query string and hence making the variables in it available in the $_GET array. Each item in the query string is split at the & and put into the array for you. This is one of the nice features of PHP. Let’s take a look at another example. Assume we have a script named “print.php”, let’s submit some stuff to it through the GET method.



Look at everything after the ?, that’s the query string. It is formatted like: name=value (var “name” has value of whatever “value” is) and each pair is separated by a &. We can now use the $_GET array to retrieve these values in our script.



Have a play around with these arrays, get used to using them.

    Note:
$_POST and $_GET were introduced in PHP 4.1.0, if you have an older version than this you should upgrade. If you can’t, replace $_POST with $HTTP_POST_VARS and $_GET with $HTTP_GET_VARS.

Multi-dimensional Arrays


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 $_POST['inputname'] referencing a single value, it can reference an array.

Submitting Arrays Through Forms

Let’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 $_POST array is “checkboxes[]”.

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 $_POST['checkboxes'] would contain one item, if they checked two it would contain two items, and so forth.

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.

Functions

Functions 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: $nohtml = strip_tags($string); – we passed the value of $string to the function strip_tags() which then strips all the HTML and PHP tags from the string, then returns the new, tagless, string into $nohtml. So what would be the output?




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 ($nohtml). Let’s have a closer look at the syntax of a function.



  • $string – This is the variable containing our string, we know this already.
  • strip_tags – This is the name of the function we are using. All functions have () at the end. In this case we passed the function a value, when you do this you put the value you want to pass to the function within the brackets. It’s not compulsory with all functions, but just remember, value inside brackets. In this case we wanted to pass the value contained in $string. The value we pass is called a parameter or argument.
  • = – The assignment operator. We use this to assign a value to a string or array item, we already know this too.
  • $nohtml – This is the variable that the function will pass the new string back to. This is called returning a value. However, not all functions return a value, but this one does.

So the function strips the tags off the value that we pass to it, then we assign the new value from the function to $nohtml and there we have it, we used a function to modify a string.

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/Arguments

Firstly 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.
  • Functions can be passed parameters, depending on the function, some are optional, some are not. Functions can receive more than one parameter.
  • Multiple parameters are separated by commas.
  • If you submit a string as a parameter, quote it. The single quotes, double quotes thing also applies to passing parameters to functions.

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 Functions

PHP 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 "print this out" to the function. Now, when we define the function we need to give that function a name that it can use to handle the parameter passed to it. In this case I chose $string. It can be whatever you want. We could pass more than one parameter. Just give them each names when you define the function.



Returning a Value

To 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 "whatever". We could just return a string enclosed in quotes, we could just return a number, we can return a variable or an array.

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 GLOBAL

Sometimes 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 echo $thestring; it wouldn’t work. Any variable you initialisecannot automatically be used outside the function. Similarly, any variable created outside of a function cannot be used within a function by default. The term used it "global". If a variable is global it is available within a function and can be used outside it too.

There’s two main reasons why we’d need this:
  • We have a variable that we made and we want to use it in our function without passing it as a parameter.
  • A function creates a variable that we want to be available outside the function without having to return it.

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 global $length;. It makes that variable usable within the function. If you ran that code without that line the variable $length would not be usable within the function. Inside the function it would not exist. global lets the function use it too. The same applies for variables we create within a function, use global $var; and that variable will be available outside the function, too.

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.

Conditionals

Conditionals allow us to perform different statements depending on certain conditions, here is the formal for a simple if statement.



We say if(condition is true) then perform a set of actions. Let’s look at a practical example.



It kind of speaks for itself. The > means “greater than”. So “if $a (2) is greater than $b (1) print out ‘the value in $a is greather than the value in $b’”. We can also use else:



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 elseif:



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.

While

While is a function that allows us to perform actions while a condition is true. Let’s take a look at an example.



Firstly, $var++; means “increment var” meaning “add one to the value of var”. It is the same as $var = $var + 1;. Let’s go thru the steps.
  • Make $var that has the value of one.
  • Tell PHP: “while the value in $var is LESS THAN 11, perform the action in the curly brackets.
  • $var is less than 11, so start performing the actions.
  • Print out the current value of $var (1).
  • Increment value in $var (it is now 2).
  • Go back and check: “is $var less than 11?”
  • It is, so we perform the actions again, $var is now 3....

This process repeats until $var reaches the value of 11, it is then no longer LESS THAN 11, it is 11, so the while loop doesn’t execute again and the script finishes. So all the above script would do is count out one to ten.

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.

More

The 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.

Resources


  • PHP.net – PHP.net, the only resource you really need to learn more about PHP. Exhaustive online manual and function references.
  • PHP Builder – Big PHP site featuring articles and tutorials and very active discussion boards.
  • Google – Google, the biggest search engine on the internet. You can find many more PHP resources if you just search.

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.

Good luck.



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


No Comments for this page.

You Must be logged in or a member to comment.


Tutorial Stats

Tutorial Stats

321,316 Views
9 Total Comments
5 Rating of 5 (2 Votes)

Options

Tutorial Options

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

Articles

Related    

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



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