How to Write PHP Scripts
![]() |
This article needs to be
converted to wikiHow format as specified by the Writer's
Guide. You can help by editing it now and then removing this notice. Notice added on 2008-01-14. |
||||
"PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML." Over 20 million websites use PHP today. Sites like eBay, Yahoo, and NASA are using PHP. Most website tasks can be tackled using PHP, and the great thing is it's not hard to learn. _
Contents |
[edit] Steps
[edit] Part I
- PHP is a widely popular server side scripting language used on over 20 million websites including industry-leaders like eBay, Yahoo!, and NASA. If NASA trusts PHP, then I think it's safe to say PHP is very solid.
- PHP scripts are embedded right inside plain HTML documents and are processed on the server computer, sending pure HTML back to the visitors browser. Calling PHP a server-side scripting language means the scripts are read, processed, and output is written from the server computer.
- PHP scripting has many benefits for developers over other scripting languages. Unlike JavaScript and VBScript, PHP doesn't require a special browser or plug-ins to run. All browsers can view pages created with PHP. The PHP Engine is also free for anyone to download and install, and can be installed on Windows, Linux, and Macintosh machines.
[edit] Who Is This Article Written For
- This article assumes you have no previous programming training.
- If you do have previous programming training, then the concepts explained here should come easy. PHP borrows heavly from the C/C++ programming language.
[edit] F.A.Q
- Q: What does PHP stand for?
- A: PHP is a recursive acronym that stands for PHP: Hypertext Preprocessor.
- Q: What do I need to run PHP scripts?
- A: See the section below, Things You'll Need.
[edit] Things You'll Need
- The Apache Web Server (Win32) - How to Install the Apache Web Server on a Windows PC
- PHP (Win32) - How to Install the PHP Engine on Your Windows PC
- A Text Editor - Windows Notepad will work for this. However, Notepad++ (Win) has syntax highlighting (certain sections of the code are highlighted to make it easier to read) for a number of different languages, including PHP. Alternatively, Textwrangler (Mac) has similar capabilities. Both of these are free to download from their respective websites.
- A Web Browser - Any browser will work but Mozilla Firefox is a popular choice amongst web developers.
- You will need 7-Zip or WinRAR if you want to download and extract the source codes. You don't have to download the source codes, you can just type the code into your text editor.
[edit] Conventions used in this article
There are a few keywords and images you should watch out for when reading this article.
This is an Alert Box. These boxes contain important
information.
This is the How It Works Box. These boxes precede an explanation of
how the previous script works.
[edit] Things you should know before starting
- This article assumes you've installed Apache and PHP on your computer. Anytime it's said to save a file, you are saving in the\htdocs directory inside the Apache directory.
- When saving files in Windows Notepad, wrap the filename in double quotations so that Notepad doesn't add .txt to the end of the filename. That means you would type the filename like this
- Notice the file helloworld.php has " " around it. You have to do this or Notepad will save the file as helloworld.php.txt
Your First Script
Let's jump right into writing your first script, and then I'll
explain what's going on.
Open Notepad (File>>All
Programs>>Accessories>>Notepad). You'll be using
Notepad a lot.
Type this into Notepad
<?php
- echo "Hello World!";
?>
Save this file as "helloworld.php".
Open your favorite browser and type this address in the address
bar:
http://localhost/helloworld.php
This is what you should see in your browser window
Hello World!
Nothing fancy here, but you did write your first PHP script.
![]() |
<?php
?>
These two lines tell the PHP engine that everything between them is PHP code. Everything outside the two tags is treated as HTML and ignored by the PHP engine and sent to your browser the same as any other HTML. The important thing you need to recognize here, is that PHP scripts are embedded inside regular HTML pages.
echo "Hello World!";
This line uses the echo statement (well, actually it is a construct, but more on that later). Statements are used to tell the PHP engine to do something. In this case you are telling the engine to print what is inside the quotes.
It's important to know that when I say print, I don't actually mean print. The PHP engine never actually prints anything to your screen. Any output generated by the engine is sent to your browser as HTML. Your browser doesn't even know that it's getting PHP output. As far as the browser is concerned it's getting plain HTML.
With that in mind, change the script above so that it looks like
this
<?php
-
echo "<strong>Hello World!</strong>";
?>
Save the file as "helloworld2.php", and open your browser by
using the address
http://localhost/helloworld.php
This time in your browser you'll see
Hello World!
<strong></strong>is HTML markup to print all text between the tags as bold.
This demonstrates that any output sent from the PHP engine is treated as HTML by your browser.
Let's write the same script as before, but add another echo statement.
Type this into Notepad
<?php
-
echo "Hello World!<br />";
- echo "How are you doing?";
?>
Save this as "helloworlddouble.php". When you run the script in your browser, you should see this
Hello World!
How are you doing?
<br />on the first line. This is HTML markup to insert a line break. If you didn't add this, your output would look like this
Hello World!How are you doing?
Now that you've mastered the echo statement, let's move on
to something a bit more complicated.
[edit] Variables
You can think of variables as containers for data. To manipulate data, be it numbers or names, you need to store the data in a container. The syntax for assigning data, or better called a value, into a variable is
$myVariable = "Hello World!";
In the above example, the value is "Hello World!", and the variable is $myVariable. You're telling PHP to store the value at the right of the equals sign, into the variable at the left of the equals sign.
![]() |
Now let's do something fun with a variable.
Open Notepad and type this in
<?php
- $myVariable = "Hello World!";
- echo $myVariable;
?>
Save the file as "myfirstvariable.php".
When you browse to this script with your browser, the output should look like this
Hello World!
On the first line of the script, you have defined a variable called
$myVariable, and you have inserted a value; "Hello World!". On a
line like this, you are giving the variable name on the left of the
equals sign, and the value you want to assign to it on the right of
the equals sign. From this point on in your script, unless you
change the value, $myVariable will always contain the value "Hello
World!".
The next line you should be familar with, a simple echo statement. What you need to take notice of is that the echo statement printed the value of $myVariable, and not literally "$myVariable". This shows that you can assign values to variables, and then print that value.
Variables can also contain numbers, and then those numbers can be
manipulated using simple mathematical functions. Take this next
script for example.
Type this into notepad
<?php
- $mySmallNumber = 12;
- $myLargeNumber = 356;
- $myTotal = $mySmallNumber + $myLargeNumber;
- echo $myTotal;
?>
Run this script in your browser, you should see this
368
Nothing real impressive, but you did add two variables
together.
On the first two lines, you created two variables. $mySmallNumber,
and $myLargeNumber. You have inserted into these variables two
values, 12 and 356. Now you see that you can store numbers inside
variables.
On the third line you have created another variable called $myTotal. With this variable, you have stored the value of $mySmallNumber PLUS $myLargeNumber. Since $mySmallNumber has the value of 12 stored in it, and $myLargeNumber has the value of 356 stored in it, what you have done is stored the value of 12 + 356 into the $myTotal variable. The value stored in $myTotal is 368.
And the last line is an echo statement which outputs the value of $myTotal.
[edit] Conclusion
In the first part of this article you have learned to output basic text to your browser, and you have learned about variables. While these things might not seem amazing, many of the things you will do in PHP rely on these basic fundamentals.
In the next part of this article, you will learn about data types and how to further manipulate variables.
[edit] Part II
[edit] Things You'll Need
- A working PHP installation (You should have this if you have been through the first tutorial)
[edit] Introduction
- This tutorial covers datatypes along with the if statement. These will build the foundation to any program you wish to write.
- The if statement allows the language to ask questions. This adds flexibility that is necessary for even the most basic projects you could wish to complete. This construct allow the program to conditionally execute behavior.
[edit] Datatypes
- Datatypes differentiate one piece of data from another. There are an infinite number of datatypes in PHP, because the language allows you to define your own datatypes. However, that is beyond the scope of this tutorial. The three datatypes that we will be concerned with are strings, numbers and Booleans.
Numbers
- Of these datatypes, numbers are the most fundamental. Numbers are numbers, that’s really about all there is to them. All basic arithmetic operations exist in PHP and numbers react to them exactly as you would expect. It is easy to assign a number value to a variable:
$myVar = 3;
$myVar = 3.0;
Strings
- A string represents an indeterminate list of characters. These characters can be anything, Greek letters, numbers, anything that can be represented in a computer. Most data that will be placed on the page will be from string datatypes. Strings must be enclosed by either double or single quotes. You declare a string variable like this:
$myStringVar= “hello world”;
$myStringVar2 = ‘hello world’;
- Variables can be placed inside strings in what is called inline replacement. This allows you to replace the variable with whatever you would like. For instance:
$name = “John”;
$message = “Hello $name”;
- Would render as “Hello John”. This allows you to make messages that vary depending on who is visiting the site.
Booleans
- Booleans represent a true or false value. Think of it as a yes
or no. Booleans are vital in PHP as answers to questions that your
program will ask. PHP will treat anything as a Boolean if you place
it in a Boolean context. PHP treats a lot of things as true, while
relatively few things are false. The following objects are treated
as false:
-
- The number 0.
- The number 0.0.
- The empty string "", We'll get to this.
- The string "0".
-
- This is by no means a complete list of false values; however, it is everything that is false within the scope of this tutorial.
[edit] Branching Construct
- Branching constructs are the fundamental decision makers in PHP. When you use a branching construct you are able to specify behavior based on a condition. Using this behavior allows you to check for errors in data, verify that a user has the correct credentials to access a portion of your site, or anyplace else that you want your program to conditionally execute code.
If Statement
- The if statement is the workhorse branching construct. Once you understand this, you will find yourself using it in almost every program that you write. An if statement allows the program to ask a yes/no question and then execute a specified behavior depending on the answer. The if statement can be used a few different ways. The first is to execute a behavior if the answer to the question is true and do nothing if it is false:
if($myVar) {
echo “myVar is true”;
}
- In this instance, “myVar is true” would be output to the page only if the value of $myVar were true. (See the Booleans section for questions about what is true in PHP).
- This is great, but now you say, “What if I want to do something if my question is false”. That’s easy. You use an else with the if. Here is how:
if($myVar) {
echo “myVar is true”;
}
else {
echo “myVar is false”;
}
- Here we have a behavior for when $myVar is true, and then an else statement for when $myVar is false. If $myVar is true, then it evaluates as it did above. Otherwise, this statement will cause “myVar is false” to be rendered to the page.
- There is a third way to use the if statement that allows you to specify more than to behaviors. Its called the else if. You specify one or more conditions and then the behavior to execute if that condition is met. Here is an example:
if($myVar<0){
echo “myVar is negative”;
}
else if($myVar>0){
echo “myVar is positive”;
}
else{
echo “myVar is zero”;
}
- When used this way, you are able to specify an infinite number of possible outcomes, allowing your program to react to as many different inputs as you want.