Introduction
Up until recently, scripting on the internet was something which very few people even attempted, let alone mastered. Recently though, more and more people have been building their own websites and scripting languages have become more important. Because of this, scripting languages are becoming easier to learn and PHP is one of the easiest and most powerful yet.
What Is PHP?
PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script is run on your web server, not on the user's browser, so you do not need to worry about compatibility issues. PHP is relatively new (compared to languages such as Perl (CGI) and Java) but is quickly becoming one of the most popular scripting languages on the internet.
Why PHP?
You may be wondering why you should choose PHP over other languages such as Perl or even why you should learn a scripting language at all. I will deal with learning scripting languages first. Learning a scripting language, or even understanding one, can open up huge new possibilities for your website. Although you can download pre-made scripts from sites like Hotscripts, these will often contain advertising for the author or will not do exactly what you want. With an understanding of a scripting language you can easily edit these scripts to do what you want, or even create your own scripts.
Using scripts on your website allows you to add many new 'interactive' features like feedback forms, guestbooks, message boards, counters and even more advanced features like portal systems, content management, advertising managers etc. With these sort of things on your website you will find that it gives a more professional image. As well as this, anyone wanting to work in the site development industry will find that it is much easier to get a job if they know a scripting language.
What Do I Need?
As mentioned earlier, PHP is a server-side scripting language. This means that, although your users will not need to install new software, you web host will need to have PHP set up on their server. It should be listed as part of your package but if you don't know if it is installed you can find out using the first script in this tutorial. If you server does not support PHP you can ask your web host to install it for you as it is free to download and install. If you need a low cost web host which supports PHP I would recommend HostRocket.
Writing PHP
Writing PHP on your computer is actually very simple. You don't need any specail software, except for a text editor (like Notepad in Windows). Run this and you are ready to write your first PHP script.
Declaring PHP
PHP scripts are always enclosed in between two PHP tags. This tells your server to parse the information between them as PHP. The three different forms are as follows:
Code: Select all
<?
PHP Code In Here
?>
<?php
PHP Code In Here
php?>
<script language="php">
PHP Code In Here
</script>
Your First Script
The first PHP script you will be writing is very basic. All it will do is print out all the information about PHP on your server. Type the following code into your text editor:
Code: Select all
<?
phpinfo();
?>
One other thing you should notice in this example is th
at the line ends in a semicolon. This is very important. As with many other scripting and programming languages nearly all lines are ended with a semicolon and if you miss it out you will get an error.
Finishing and Testing Your Script
Now you have finished your script save it as phpinfo.php and upload it to your server in the normal way. Now, using your browser, go the the URL of the script. If it has worked (and if PHP is installed on your server) you should get a huge page full of the information about PHP on your server.
If your script doesn't work and a blank page displays, you have either mistyped your code or your server does not support this function (although I have not yet found a server that does not). If, instead of a page being displayed, you are prompted to download the file, PHP is not installed on your server and you should either serach for a new web host or ask your current host to install PHP.
It is a good idea to keep this script for future reference.
Part 2 - Displaying Information & Variables
Introduction
In the last part of the tutorial I explained some of the advantages of PHP as a scripting language and showed you how to test your server for PHP. In this part I will show you the basics of showing information in the browser and how you can use variables to hold information.
Printing Text
To output text in your PHP script is actually very simple. As with most other things in PHP, you can do it in a variety of different ways. The main one you will be using, though, is print. Print will allow you to output text, variables or a combination of the two so that they display on the screen.
The print statement is used in the following way:
Code: Select all
print("Hello world!");
print is the command and tells the script what to do. This is followed by the information to be printed, which is contained in the brackets. Because you are outputting text, the text is also enclosed instide quotation marks. Finally, as with nearly every line in a PHP script, it must end in a semicolon. You would, of course, have to enclose this in your standard PHP tags, making the following code:
Code: Select all
<?
print("Hello world!");
?>
Hello world!
on the screen.
Variables
As with other programming languages, PHP allows you to define variables. In PHP there are several variable types, but the most common is called a String. It can hold text and numbers. All strings begin with a $ sign. To assign some text to a string you would use the following code:
Code: Select all
$welcome_text = "Hello and welcome to my website.";
Strings are case sensitive so $Welcome_Text is not the same as $welcome_text
String names can contain letters, numbers and underscores but cannot begin with a number or underscore
When assigning numbers to strings you do not need to include the quotes so:
Code: Select all
$user_id = 987
Outputting Variables
To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:
Code: Select all
<?
$welcome_text = "Hello and welcome to my website.";
print($welcome_text);
?>
Formatting Your Text
Unfortunately, the output from your PHP programs is quite boring. Everything is just output in the browser's default font. It is very easy, though, to format your text using HTML. This is because, as PHP is a server side language, the code is executed before the page is sent to the browser. This means that only the resulting information from the script is sent, so in the example above the browser would just be sent the text:
Hello and welcome to my website.
This means, though, that you can include standard HTML markup in your scripts and strings. The only problem with this is that many HTML tags require the " sign. You may notice that this will clash with the quotation marks used to print your text. This means that you must tell the script which quotes should be used (the ones at the beginning and end of the output) and which ones should be ignored (the ones in the HTML code).
For this example I will change the text to the Arial font in red. The normal code for this would be:
Code: Select all
<font face="Arial" color="#FF0000">
</font>
e to:
Code: Select all
<font face=\"Arial\" color=\"#FF0000\">
</font>
Code: Select all
print("<font face=\"Arial\" color\"#FF0000\">Hello and welcome to my website.</font>");
Hello and welcome to my website.
because it has only been sent the code:
Code: Select all
<font face="Arial" color="#FF0000">Hello and welcome to my website.</font>
Part 3 - IF Statements
Introduction
Over the past two parts I have shown you the basics of text in PHP and how to store it as variables. In this part of the tutorial I will show you how to use IF statements to make decisions in your scripts.
The Basics Of IF
If statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed.
IF Strucure
The structure of an IF statement is as follows:
Code: Select all
IF (something == something else)
{
THEN Statement
} else {
ELSE Statement
}
The most common use of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:
Code: Select all
if ($username == "webmaster")
Constructing The THEN Statement
To add to your script, you can now add a THEN statement:
Code: Select all
if ($username == "webmaster") {
echo "Please enter your password below";
}
Constructing The ELSE Statement
Adding The ELSE statement is as easy as the THEN statement. Just add some extra code:
Code: Select all
if ($username == "webmaster") {
echo "Please enter your password below";
} else {
echo "We are sorry but you are not a recognised user";
}
Other Comparisons
There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g.
Code: Select all
if ($enteredpass == $password)
Code: Select all
if ($age < "13")
Code: Select all
if ($date > $finished)
Code: Select all
if ($name == "" || $email == "" || $password == "") {
echo "Please fill in all the fields";
}
Introduction
In the last parts of this tutorial I have showed you how to deal with text and variables in PHP and how you can use IF statements to compare them and to make decisions. In this part I am going to show you how to use another important part of PHP, loops.
The WHILE Loop
The WHILE loop is one of the most useful commands in PHP. It is also quite easy to set up and use. A WHILE loop will, as the name suggests, execute a piece of code until a certain condition is met.
Repeating A Set Number Of Times
If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words "Hello World" 5 times you could use the following code:
Code: Select all
$times = 5;
$x = 0;
while ($x < $times) {
echo "Hello World";
++$x;
}
After the echo line which prints out the text, there is another very important line:
Code: Select all
++$x;
Code: Select all
$x = $x + 1;
Using $x
The variable counting the number of repeats ($x in the above example) can be used for much more than just counting. For example if you wanted to create a web page with all the numbers from 1 to 1000 on it, you could either type out every single one or you could use the following code:
Code: Select all
$number = 1000;
$current = 0;
while ($current < $number) {
++$current;
echo "$current<br>";
}
The other reason for this is that, if the ++$current; line was after the echo line, the loop would also stop when the number showed 999 because it would check $current which would equal 1000 (set in the last loop) and would stop, even though 1000 had not yet been printed.
Arrays
Arrays are common to many programming languages. They are special variables which can hold more than one value, each stored in its own numbered 'space' in the array. Arrays are extremely useful, especially when using WHILE loops.
Setting Up An Array
Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 5 names in it:
Code: Select all
$names[0] = 'John';
$names[1] = 'Paul';
$names[2] = 'Steven';
$names[3] = 'George';
$names[4] = 'David';
Reading From An Array
Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the number of the piece of data in the array. So if I wanted to print out the third name I could use the code:
Code: Select all
echo "The third name is $names[2]";
The third name is Steven
Using Arrays And Loops
One of the best uses of a loop is to output the information in an array. For instance if I wanted to print out the following list of names:
Name 1 is John
Name 2 is Paul
Name 3 is Steven
Name 4 is George
Name 5 is David
I could use the following code:
Code: Select all
$number = 5;
$x = 0;
while ($x < $number) {
$namenumber = $x + 1;
echo "Name $namenumber is $names[$x]<br>";
++$x;
}
Part 5 - Email With PHP
Introduction
One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.
The Mail Command
Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:
Code: Select all
mail($to,$subject,$body,$headers);
The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an emai but you can also include other headers like cc and bcc.
Sending An E-mail
Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:
Code: Select all
$to = "[email protected]";
$subject = "ROBOT.LK is Great";
$body = "ROBOT.LK is the best Developer Community";
$headers = "From: [email protected]\n";
mail($to,$subject,$body,$headers);
echo "Mail sent to $to";
ROBOT.LK is the best Developer Community
and the e-mail will be from [email protected]. It will also output the text:
Mail sent to [email protected]
to the browser.
Formatting E-mail
Something you may have noticed from the example is that the From line ended with \n. This is actually a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.
The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.
Mail Without Variables
The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:
mail("[email protected]","ROBOT.LK is Great","ROBOT.LK is the best Developer Community","From: [email protected]\n");
But that would make your code slightly harder to read.
Error Control
As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:
Code: Select all
if(mail($to,$subject,$body,$headers)) {
echo "An e-mail was sent to $to with the subject: $subject";
} else {
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid";
}
Part 6 - PHP With Forms
Introduction
In the last part, I showed you how to use PHP to send e-mail messages using a script. In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts useful.
Setting Up Your Form
Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in how to write your form but I will show you three of the main pieces of code you must know:
Code: Select all
<input type="text" name="thebox" value="Your Name">
Code: Select all
<textarea name="message">
Please write your message here.
</textarea>
Code: Select all
<input type="submit" value="Submit">
All the elements for your form must be enclosed in the <form> tags. They are used as follows:
Code: Select all
<form action="process.php" method="post">
Form elements and formatting etc.
</form>
It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser's address bar.
Getting The Form Information
The next step is to get the data the form has submitted into your script so that you can do something with it. This is. There are basically two different methods of getting the data into PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The benefit of GET, though is that you can submit information to the script without a form, by simply editing the URL.
This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:
yourpage.php?user=martin
could show Martin's page and:
yourpage.php?user=shane
could show Shane's page, using the same script.
It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:
yourpage.php?user=martin&referrer=yoursite&area=8
These could all be accessed separately using the GET variables user, referrer and area.
To get a variable which has been sent to a script using the POST method you use the following code:
$variablename=$_POST['variable'];
which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variablename.
Similarly, if you are using the GET method you should use the form:
$variablename=$_GET['variable'];
This should be done for each variable you wish to use from your form (or URL).
Creating The Form To Mail Script
To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user's comments to you.
Firstly, create this form for your HTML page:
Code: Select all
<form action="mail.php" method="post">
Your Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br><br>
Comments<br>
<textarea name="comments"></textarea><br><br>
<input type="submit" value="Submit">
</form>
Code: Select all
<?
function checkOK($field)
{
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}
}
$name=$_POST['name'];
checkOK($name);
$email=$_POST['email'];
checkOK($email);
$comments=$_POST['comments'];
checkOK($comments);
$to="[email protected]";
$message="$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address was: $email";
if(mail($to,"Comments From Your Site",$message,"From: $email\n")) {
echo "Thanks for your comments.";
} else {
echo "There was a problem sending the mail. Please check that you filled in the form correctly.";
}
?>
The first part of that script may look a bit strange:
Code: Select all
function checkOK($field)
{
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}
}
The lines:
Code: Select all
checkOK($name);
Part 7 - Final Notes
Introduction
In the past 6 parts of this tutorial I have shown you the basics of writing PHP. In this final part I will show you a few small things which don't really warrant a section of their own.
Comments
As with any programming language, it is quite important to comment in your script. If you are working on a script with someone else you must let them know what you code does and if you are distributing your script you will need to show people how to edit it. Even if you are the only one who will use your script it is useful to comment so that you can edit it at a later date.
In PHP there are two ways you can comment. One way is used for single line comments and the other is used mainly for comments that go over one line. A single line comment is written as follows:
Code: Select all
// Your comment can go in here
Code: Select all
print "Hello $name"; // Welcome to the user
Code: Select all
/* The following piece of code will take the input
the user gave and will check that it is valid before
adding it to the database */
Print, Echo and HTML
As you may have noticed during this tutorial I have actually used 4 different ways of outputting information to the browser:
Code: Select all
echo("Text here");
echo "Text here";
print("Text here";
print "Text here";
Code: Select all
<?
Top PHP code in here
?>
HTML Code
<?
Bottom PHP code in here
?>
Code: Select all
<?
IF Statement {
?>
HTML For IF Being Correct
<?
} else {
?>
HTML For IF Being Wrong
<?
}
?>
One Line Prints
Being able to place HTML code into your PHP is very useful, but what happens if you want to put the value of a variable into the code. Unlike when using an echo or print statement, you can't just put in the variable name as this section is not actually part of the PHP code. Instead you must just put in a little PHP.
For example if you wanted to print someone's name from a script with HTML formatting you would do the following:
Code: Select all
<font face="Arial" size="7" color="red"><b><? echo($variablename); ?></b></font>
Code: Select all
<? echo($variablename); ?>
Code: Select all
<?
echo($variablename);
?>