__Welcome to PHP Tutorial

What Is PHP?PHP (PHP: Hypertext Preprocessor) is a server-side scripting language intended to help web developers build dynamic web sites quickly.
How Does PHP Work?PHP scripts are executed on the server, before the web page is displayed to the user (this is what we mean by "server-side"). The user only sees the end result, which consists of client-side markup and scripts (i.e. HTML, JavaScript, CSS etc). Therefore, the user/browser doesn't actually see any PHP code. If the user views the source code, all they would see is HTML, JavaScript, CSS etc - they wouldn't see any PHP code.
This happens because, whenever the server processes a file with the .php extension, it knows to look for PHP code. When it encounters the PHP code, it processes it. Generally, the same .php file will also have client side code such as HTML. The server knows to process the PHP bits and output the client-side bits. You, as the programmer, determine which pieces of HTML will be displayed and when. You do this using PHP code.
What Can PHP Do?PHP enables you to build large, complex, and dynamic websites. PHP can also increase your productivity enormously, both in development time and maintenance time.
Using PHP, you can build websites that do things such as:
  • Query a database
  • Allow users to upload files
  • Create/read files on the server (for example, the files that your users upload)
  • Have a "member's area" (i.e. via a login page)
  • Have a shopping cart
  • Present a customized experience (for example, based on users' browsing history)
  • Much, much more
What Do I Need to Create PHP Code?You can create PHP code using the same equipment you use when creating HTML. That is, a computer with the following software:
  • Text editor. For example, Notepad (for Windows), Pico (for Linux), or Simpletext (Mac). You could use a special HTML or PHP editor if you like but it's not needed.
  • Web Browser. For example, Internet Explorer or Firefox.
What Do I Need to Run PHP?To run the PHP pages you create, you need a computer with the following software:
  • A web server (such as IIS, Apache etc)
  • PHP
If you don't have these installed, you have a couple of options (apart from giving up!). The next lesson will point you in the right direction.

If you don't have PHP installed on your computer, here are your best options:
  • Download and install PHP
  • Find a hosting provider that supports PHP (most hosting providers do)
You may already have a PHP hosting provider. If this is the case, all you need to do is upload your PHP files the same way you would upload any HTML file. If you don't have a hosting provider, check out these shared hosting reviews for a comparison of some of the top shared hosting providers. You will also find links to dedicated hosting and VPS hosting reviews.
Downloading PHPEven if you have a PHP hosting provider, I recommend that you install PHP on your own local environment anyway. That way, you'll become more familiar with PHP, plus, you should always have a development environment that is separate to your production environment.
You can download PHP from the PHP website here:
http://www.php.net/downloads.php
To assist with the installation, you can view the PHP documentation here:
http://www.php.net/docs.php (Just select your preferred language).
Or, you can jump straight to the English version of the installation notes here:
http://www.php.net/manual/en/install.php
Installing a Web ServerIf your machine doesn't have a web server installed, you will need to install one before you install PHP. There are many different web servers available to choose from, so you need to choose which one you prefer. Two of the more popular web servers are:
  • Apache
  • Internet Information Services (IIS)
If you're using Windows Server or Windows XP, it's possible your machine already has IIS installed. You can check to see if you have a web server installed by looking under "Administration Tools" for "Internet Information Services". You can usually find IIS at either Start > Program Files > Administration Tools or Start > Control Panel > Administration Tools.
If it's not installed, you may find that you can add IIS as an optional Windows component. To do this:
  • Go to Start > Control Panel > Add or Remove Programs > Add/Remove Windows Components)
  • If you see the option "Internet Information Services (IIS), select it (if it's already selected it's already installed).
  • Click Next
This should install IIS for you. Once you've installed IIS, open a browser and type http://localhost. This should display the default IIS homepage. You can change this by replacing the files in the default directory (or changing the default directory location). The default directory is normally at C:\Inetpub\wwwroot. This is where you can place your .php files.

The PHP syntax is based on C, Java, and Perl, so if you've used any of those languages PHP will look familiar to you. Creating a PHP file is similar to creating an HTML file. In fact, most PHP files are a mixture of PHP code and HTML.
Creating a PHP FileTo create a PHP file, simply do the following:
  1. Create a new file in your favorite editor
  2. Type some PHP code
  3. Save the file with a .php extension
The .php extension tells the web server that it needs to process this as a PHP file. If you accidentally save it with a .html extension the server won't process your PHP code and the browser will just output it all to the screen.
OK, so that sounds easy. My guess is that you already know how to create a new file and save it, so let's concentrate on the other bit - the "type some PHP code" bit.
Basic Code SyntaxScripting BlocksEvery block of PHP code must start with <?php and end with ?>. The following example outputs the text "PHP is easy!" to the screen:

<html>
<head>
<title>PHP Syntax Example</title>
</head>
<body>
<?php
echo "PHP is easy!";
?>

</body>
</html>

Note: If your server supports it, you can leave off the php bit (so that it starts off like this <? echo...), but I'd recommend you keep it. This way, you won't run into any compatibility problems that you could have easily avoided.
Semi-ColonsYou need to place a semi-colon (;) at the end of each line of PHP code. This tells the server that a particular statement has finished.
CommentsIn the programming world, "comments" refer to small pieces of narrative within the code that can be useful in assisting other programmers interpret the meaning of the code. They can also be useful to yourself if you need to return to a piece of code many months (or years) after you'd written it. These comments aren't displayed to the user, instead, the server ignores them - they are purely for the programmers!
To write a comment in PHP, you prefix single line comments within two forward slashes (//) or, if the comment spans multiple lines, you need to open the whole block with a forward slash and asterisk (/*) then close it with an asterisk and forward slash (*/).
Example

<?php

// Single line comment

/*
This comment is so
long that it spans
multiple lines.
*/

?>

White Space, Carriage Returns, etcYou can use tabbing, spaces, carriage returns etc to indent and format your code - this won't cause any issues for the PHP interpreter. As long as you don't forget to close each line with a semi-colon.
Displaying the OutputTo display PHP files in a browser, you need to type the full http path. For example, something like this: http://localhost/php_syntax_example.php. In other words, you can't view the file using your file system's path (like you can with HTML files). For example, you can't just type something like this: C:\inetpub\wwwroot\php_syntax_example.php.
Using the http path means that you are accessing the file via the web server. The web server knows that any file with a .php extension needs to be processed by PHP.


Variables are named "containers" that allow you to store a value. This value can then be used by other parts of the application, simply by referring to the variable's name. For example, the application could display the contents of the variable to the user.
In PHP, variable names must start with a dollar sign ($). For example:

<?php
$myVariable = "PHP is easy!";
echo $myVariable;
?>

Another ExamplePHP variables can contain strings (like the previous example), numbers, and arrays. When a variable contains a number, you can perform calculations against that value. Here's a simple calculation using variables:

<?php
$variable1 = 2;
$variable2 = 9;
$variable3 = $variable1 + $variable2;
echo $variable3;
?>

The above code results in the following:
11 ConcatenationWhen outputting multiple variables and other text to the screen, you can concatenate them (join them together) either with multiple echo statements, or by using one echo statement with a dot (.) between each part.
Here's an example of both methods:
Option 1:

<?php
$variable1 = 2;
$variable2 = 9;
$variable3 = $variable1 + $variable2;
echo $variable1;
echo " + ";
echo $variable2;
echo " = ";
echo $variable3;

?>

Option 2 (less code):

<?php
$variable1 = 2;
$variable2 = 9;
$variable3 = $variable1 + $variable2;
echo $variable1 . " + " . $variable2 . " = " . $variable3;
?>

Both of the above code examples result in:
2 + 9 = 11 Variable NamesWhen creating names for your variables, you need to ensure they comply with the following naming rules:
  • All PHP variable names must start with a letter or underscore ( _ )"
  • Variable names can only contain alpha-numeric characters and underscores ( i.e. a-z, A-Z, 0-9, or _ )
  • Variable names must not contain spaces. For multi-word variable names, either separate the words with an underscore ( _ ) or use capitalization.
Many website applications rely on HTML forms so that users can perform their tasks. For example, most Content Management Systems allow users to provide content for a website by entering the content into a textarea form field, then clicking a "Save" button. When the user clicks the Save button, the form is submitted to the action page. The action page is normally specified with the action attribute of the form tag.
If you're not familar with HTML forms, see the HTML forms section of the HTML tutorial, then return to this page.
Once a form has been submitted, the form fields are made available to the action page as a special type of variable. You, as the programmer, can read these form variables by using the appropriate syntax for form variables. Form variables are stored as an array. We will be covering arrays later, but for now all you need to know is how to read each form variable.
Forms can be submitted using one of two methods: get or post. By default, a form will be submitted using the "get" method. This results in each form variable being passed via the URL. If you decide to use the "post" method, you specify this using the method attribute ( method="post" ) of the form tag.
The Get MethodIf you use the get method, your action page can access each form field using $_GET["variableName"] (where "variableName" is the name of the form field).
ExampleForm page
Display:

Code:

<form action="php_action_page.cfm" method="get">
<input name="firstName" /><br />
<input name="lastName" /><br />
<input />

Action page (php_action_page.cfm):
Here, the action page outputs the contents of the form variables that were passed from the form.

<html>
<head>
<title>PHP Form Variables Example</title>
</head>
<body>
First Name: <$php echo $_GET["firstName"]; ?><br />
Last Name: <$php echo $_GET["lastName"]; ?>
<body>

The Post MethodIf your form uses the post method, you use $_POST["variableName"].
ExampleForm page
Display:

Code:

<form action="php_action_page.cfm" method="post">
<input name="firstName" /><br />
<input name="lastName" /><br />
<input />

Action page (php_action_page.cfm):
Here, the action page outputs the contents of the form variables that were passed from the form.

<html>
<head>
<title>PHP Form Variables Example</title>
</head>
<body>
First Name: <$php echo $_POST["firstName"]; ?><br />
Last Name: <$php echo $_POST["lastName"]; ?>
<body>


You use PHP if statements when you want your program to execute a block of code only if a particular condition is true. In other words, you can tell your program "if something is true, then execute this piece of code".
Syntax
if (condition)
code to be executed if condition is true;

ExampleIn the following example, we create a variable called "favoriteFruit" and assign a value to it. We then compare the value with a string: "Pomegranate". If the two values are the same, we output some text.
The two equals signs (==) is a comparison operator (it compares the two values). If this condition is true, it displays the code within the curly braces ({ and }). The curly braces are only necessary if you're outputting multiple lines of code . If you're only outputting one line of code (like we are) they're optional.

$favoriteFruit = "Pomegranate";
if ( $favoriteFruit == "Pomegranate" )
{
echo "Your favorite fruit contains around 7% fibre.";
}

The above example results in the following:
Your favorite fruit contains around 7% fibre. If Else StatementWe can add an else to our if statement to make our application do something else if the condition is not true.
Example:

$favoriteFruit = "Fig";
if ( $favoriteFruit == "Pomegranate" )
{
echo "Your favorite fruit contains around 7% fibre.";
}
else
{
echo "Sorry, I don't know how much fibre that fruit contains.";
}


The above example results in the following:
Sorry, I don't know how much fibre that fruit contains. If... Elseif StatementLet's say we learn the fibre content of another fruit. We could then add an elseif to our if statement. That way, we could include a custom message for the new fruit. In fact, we could use elseif as many times as we like.
Example:

$favoriteFruit = "Lychee";
if ( $favoriteFruit == "Pomegranate" )
{
echo "Your favorite fruit contains around 7% fibre.";
}
elseif ( $favoriteFruit == "Lychee" )
{
echo "Your favorite fruit contains around 1.5% fibre.";
}

else
{
echo "Sorry, I don't know how much fibre that fruit contains";
}

The above example results in the following:
Your favorite fruit contains around 1.5% fibre.


In the previous lesson we used a PHP if... elseif statement in order to execute different block of code for each different condition. As mentioned, we could use as many "elseif"s as we like.
If you have many conditions, PHP switch statements are a more efficient way of doing this. The server will execute a PHP switch statement quicker than multiple "elseif"s. Also, there's actually less code for the programmer to write.
To write a PHP switch statement, you start with the switch keyword followed by the expression to evaluate (for example, a variable name). You then follow that with a case for each condition (based on the expression).
Syntax switch (expression)
{
case value1
code to be executed if the expression is equal to value1;
break;
case value2
code to be executed if the expression is equal to value2;
break;
case value3
code to be executed if the expression is equal to value3;
break;
default
(optional) code to be executed if none of the above conditions are true.
break;
}

ExampleIn the following example, we declare a variable called $favoriteVege and assign a value to it. We then execute a switch statement in order to display a different string depending on the value of the variable.
Don't forget to end each case with a break;. This is required, otherwise all cases would be displayed.
$favoriteVege = "Fennel";
switch ($favoriteVege)
{
case "Gourd":
echo "Your favorite vegetable has around 40 kilojoules of energy!";
break;
case "Artichoke":
echo "One of those has around 105 kilojoules of energy!";
break;
case "Cassava":
echo "One of those has around 550 kilojoules of energy";
break;
case "Potato":
echo "That would be around 460 kilojoules of energy";
break;
default:
echo "Sorry, don't know how much energy that vegetable contains.";
break;
}

The above code results in the following:
Sorry, don't know how much energy that vegetable contains.  PHP arrays allow you to store groups of related data in one variable (as opposed to storing them in separate variables). Storing data like this in an array has many benefits. For example, if you have a lot of data, you could populate the array programmatically. You could also output the contents programatically - all you need to know if the name of the array.
There are 3 different types of PHP arrays:
  • Numeric arrays
  • Associative arrays
  • Multidimensional arrays
Numeric ArraysNumeric arrays use a number as the "key". The key is the unique identifier, or ID, of each item within the array. We can use this ID later when working with the contents within the array - we don't need to know the item's value, just the ID.
Note that numbering starts at zero.
Creating Numeric ArraysYou can choose between the following options when creating an array. Both of these options have the same result.
  • Option 1 - Manual key assignment
    When creating an array this way, you assign each "key" as a number within open and closing square brackets ([ and ]).
    $arrayName[0] = "Value1";
    $arrayName[1] = "Value2";
    $arrayName[2] = "Value3";

  • Option 2 - Automatic key assignment
    When using this method to create an array, you don't need to assign the key - PHP will do that for you.
    $arrayName = array("Value1", "Value2", "Value3");

Displaying the Array ContentsYou can work with each value in an array by referring to its key. For example, to select the 2nd value in an array, we would do this: $arrayName[1]. Just a reminder that numbering starts at zero, so the 2nd item actually uses the number one as it's key.
Example:
$fruit = array("Apples", "Strawberries", "Blackberries");
echo $fruit[1];

The above code results in:
Strawberries Associative ArraysAssociative arrays are similar to numeric arrays but, instead of using a number for the key, we use a value. We then assign another value to the key - you could think of it as two values for the price of one!
Creating Associative ArraysAs with creating numeric arrays, there are two options for creating associative arrays in PHP (although in both cases, we have to create the key manually).
  • Option 1
    $arrayName['keyName'] = "Value1";
    $arrayName['keyName'] = "Value2";
    $arrayName['keyName'] = "Value3";

  • Option 2
    $arrayName = array("keyName"=>"Value1", "keyName"=>"Value2", "keyName"=>"Value3");

Displaying the Array ContentsYou can display the contents of associative arrays just as you would with numeric arrays - by referring to it's key.
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"];

The above code results in the following:
Artichoke: 105 kilojoules Multidimensional ArraysMultidimensional arrays allow you to put an array inside another array. In other words, the contents of the array is another array. You can do this as many times as you wish - you could have an array inside another array, which is inside another array, etc
The following diagram demonstrates this. We have an array called "Food", which contains 3 arrays (called "Fruit", "Vegetables", "Grains"). Each of these arrays contain their own arrays (one for each food within that group).
Food Fruit Apples Bananas Oranges Vegetables Carrots Potatoes Grains Oatbran Creating a Multidimensional ArrayWe can create the above array using the following code:
$Food = array
(
"Fruit"=>array
(
"Apples",
"Bananas",
"Oranges",
),
"Vegetables"=>array
(
"Carrots",
"Potatoes",
),
"Grains"=>array
(
"Oatbran",
)
);

PHP while loops allow you to execute the same piece of code continuously while a certain condition is true. Once the condition becomes false, the program will break out of the loop and continue processing the rest of the page.
Syntax while (condition)
{
Code to be executed while the condition is true;
}

ExampleThis example executes the same piece of code while the "sharePrice" variable is less than or equal to 10. With each iteration through the loop, we increment the value of $sharePrice by 1. This means the value of $sharePrice will eventually become greater than 10, which will result in the end of the loop, and the rest of the page will be processed.
$sharePrice = 1;
while ($sharePrice <= 10)
{
echo "The share price is " . $sharePrice . ". Don't sell yet. <br />";
$sharePrice = $sharePrice + 1;
}
echo "The share price is " . $sharePrice . ". SELL NOW!";

The above code results in:
The share price is $1. Don't sell yet.
The share price is $2. Don't sell yet.
The share price is $3. Don't sell yet.
The share price is $4. Don't sell yet.
The share price is $5. Don't sell yet.
The share price is $6. Don't sell yet.
The share price is $7. Don't sell yet.
The share price is $8. Don't sell yet.
The share price is $9. Don't sell yet.
The share price is $10. Don't sell yet.
The share price is $11. SELL NOW! Do/While LoopsA do/while loop is similar to a while loop. The difference is that a do/while loop executes the code at least once before checking the condition. Therefore, if the condition is false, a do/while loop will execute once. A while loop, on the other hand, won't execute the code at all if the condition is false.
ExampleThis example demonstrates the difference between a while loop and a do/while loop.
  • While Loop
    $sharePrice = 15;
    while ($sharePrice <= 10)
    {
    echo "The share price is " . $sharePrice . ". Don't sell yet. <br />";
    $sharePrice = $sharePrice + 1;
    }
    echo "The share price is " . $sharePrice . ". SELL NOW!";

    The above code results in:
    The share price is 15. SELL NOW!
  • Do/While Loop
    $sharePrice = 15;
    do {
    echo "The share price is " . $sharePrice . ". Don't sell yet. <br />";
    $sharePrice = $sharePrice + 1;
    }
    while ($sharePrice <= 10);
    echo "The share price is " . $sharePrice . ". SELL NOW!";

    The above code results in:
    The share price is 15. Don't sell yet.
    The share price is 16. SELL NOW!  PHP for loops allow you to execute the same piece of code for a specified number of times. Once the specified number has been reached, the program will break out of the loop and continue processing the rest of the page.
    SyntaxA PHP for loop requires 3 parameters. The 1st parameter sets a counter, the 2nd parameter defines how high the counter should get before breaking from the loop, the 3rd parameter is used to increment the counter.
    for (set counter, condition, increment counter)
    {
    Code to be executed while the counter is less than the specified count;
    }

    ExampleWe can use the same topic we used in the previous lesson on "while" loops. In fact, for loops are more suited to this type of usage than while loops.
    for ($sharePrice = 1; $sharePrice <= 10; $sharePrice++)
    {
    echo "The share price is " . $sharePrice . ". Don't sell yet. <br />";
    }
    echo "The share price is " . $sharePrice . ". SELL NOW!";

    The above code results in:
    The share price is $1. Don't sell yet.
    The share price is $2. Don't sell yet.
    The share price is $3. Don't sell yet.
    The share price is $4. Don't sell yet.
    The share price is $5. Don't sell yet.
    The share price is $6. Don't sell yet.
    The share price is $7. Don't sell yet.
    The share price is $8. Don't sell yet.
    The share price is $9. Don't sell yet.
    The share price is $10. Don't sell yet.
    The share price is $11. SELL NOW! For/Each LoopsA for/each loop allows you to loop through arrays. It will execute code continuously until it has looped through every item in the array. Once it has done that, it will continue on processing the rest of the page.
    $fruit = array("Apples", "Strawberries", "Blackberries");
    foreach($fruit as $value)
    {
    echo $value . "<br />";
    }

    The above code results in:
    Apples
    Strawberries
    Blackberries PHP operators are characters (or sets of characters) that perform a special operation within the PHP code. For example, when you use the equals sign ( = ) to assign a value to a variable, you are using an assignment operator. When you add two numbers together using a plus sign ( + ), you are using an arithmetic operator.
    Here's a list of the various PHP operators:
    Artithmetic Operators OperatorDescription +Addition -Subtraction *Multiplication /Division %Modulus (remainder of a division) ++Increment --Decrement Assignment Operator OperatorDescription =Assign +=Increments, then assigns -=Decrements, then assigns *=Multiplies, then assigns /=Divides, then assigns %=Modulus, then assigns Comparison Operators OperatorDescription ==Is equal to !=Is not equal to >Greater than >=Greater than or equal to <Less than <=Less than or equal to Logical Operators OperatorDescription &&And operator. Performs a logical conjunction on two expressions (if both expressions evaluate to True, result is True. If either expression evaluates to False, result is False) ||Or operator. Performs a logical disjunction on two expressions (if either or both expressions evaluate to True, result is True). !Not operator. Performs logical negation on an expression. Concatenation Operators OperatorDescription .Concatenate (join two strings together) Sometimes you might find yourself writing the same piece of code over and over again. You might even find yourself "copy/pasting" code so that you can re-use it in another part of your application. The problem with doing this is, you now have more code to maintain. For example, if you want to change the code, you need to change it in many different places. A better idea would be to put that code into a function.
    PHP functions are self contained blocks of code that perform a specified "function". A function often accepts one or more "parameters" (also referred to as "arguments") which you can "pass" to it. By providing a different parameter to the function, you get a different result (depending on what the function actually does).
    Creating PHP FunctionsTo create a PHP function, follow these steps:
    1. Think of a name for the function. Make it short but descriptive. It should describe what the function actually does.
    2. Type function
    3. On the same line, type the name of the function followed by opening/closing brackets ( eg, myFunction() ).
    4. Add an opening curly brace ( { )
    5. Type the code that makes up the function
    6. Finish with a closing curly brace ( } )
    Example <?php

    function writeMyFavoriteFruit()
    {
    echo "My favorite fruit is pomegranate.";
    }

    ?>

    Calling PHP FunctionsThe function doesn't actually do anything until you call it. To call a function, do the following:
    1. Write the function name followed by opening and closing brackets (i.e. functionName() )
    2. Between the opening/closing brackets, provide any parameters the function requires. If it doesn't require any parameters you can leave it blank.
    ExampleIn this example, we create the same function we created in the previous example. We then call that function:
    <?php

    function writeMyFavoriteFruit()
    {
    echo "My favorite fruit is pomegranate.";
    }

    writeMyFavoriteFruit();

    ?>

    The above code results in the following:
    My favorite fruit is pomegranate. Passing ParametersThe previous example is a very simplistic version of a function. We could improve this function by allowing it to accept a parameter. For example, imagine if, at the time we called the function, we could pass it the name of a fruit. The function could then display the name of that fruit (instead of displaying "pomegranate" every time).
    Example 1 <?php
    function writeMyFavoriteFruit($fruitName)
    {
    echo "My favorite fruit is: " . $fruitName;
    }

    writeMyFavoriteFruit("Watermelon");
    ?>

    The above code results in the following:
    My favorite fruit is: Watermelon This is one of the things that make functions so cool. For example, by accepting a parameter (such as the fruit name), we could let our website users provide us with the name of their favorite fruit. Behind the scenes, we could put that fruit into a variable, then pass that variable to our function. The function could then display the name of their favorite fruit (instead of "pomegranate"!).
    Example 2In this example, the fruit name is supplied as a variable. For the purposes of this tutorial, we set the variable to a hard-coded string, but there's no reason this couldn't be a value provided by the user (for example, a value from a form).
    <?php
    $userFavFruit = "Watermelon";

    function writeMyFavoriteFruit($fruitName)
    {
    echo "My favorite fruit is: " . $fruitName;
    }

    writeMyFavoriteFruit($userFavFruit);
    ?>

    The above code results in the following:
    My favorite fruit is: Watermelon Return ValuesIn the previous examples, our functions simply displayed a string to the user. Sometimes, you might not want your function to automatically display the result. Sometimes you might just want the function to return the result to you so that you can use it for your own programmatical purposes. That way, it's your choice whether you display it to the user, or do something else with the result.
    To create a return value, you type return followed by the value you want to return.
    Example <?php
    function sum($number1,$number2)
    {
    $total = $number1 + $number2;
    return $total;
    }

    echo sum(100,4);
    ?>

    The above code results in the following:
    104  A PHP "Include" is a file that is included into another file. This concept allows you to re-use content throughout your website.
    For example, you could have a standard header and footer on every page of your website. Instead of copying/pasting this code on to every page, you could simply place your header code into one include file and your footer code into another include file. Then, on every page, all you need to do is refer to the header and footer include files. You can do this either using the include() function or the require() function.
    There's only a small difference between the include function and the require function. More on that below.
    The include() FunctionTo include a file using the include() function, you simply call the function (as you would any other function) and insert the file path as a parameter.
    Usage Example <?php

    include("header.php");

    echo "Here's the rest of the page.";

    include("footer.php");

    ?>

    The require() FunctionUsage of the require() function is exactly the same as the include() function - simply call the function and pass the path of the include file.
    The difference between the include() and require() functions is in the way they handle errors. If the included file can't be located, the include() function will still display the rest of the page (as well as an error). The require() function, on the other hand, will simply display an error - it won't display the rest of the page.
    Usage Example <?php

    require("header.php");

    echo "Here's the rest of the page.";

    require("footer.php");

    ?>

    You can use PHP to allow your users to upload a file to the server.
    To allow users to upload a file to the server, you first need to provide a form for them to specify which file they want to upload. Once they click the submit button of the form, the action page is called. This is the page that needs to contain the PHP code to process the uploaded file.
    The Input FormBefore a user can upload a file, you need to provide them with an interface that allows them to select a file and initiate the upload.
    The following code is an example of an input form. There are a couple of important things to note about this code:
    • The action attribute points to a .php file. This is the file that will process the uploaded file.
    • There is an attribute called enctype, and its value is multipart/form-data.
    • One of the input fields has .
    <html>
    <head>
    <title>PHP File Upload Example</title>
    </head>
    <body>
    <form enc method="post" action="uploadFile.php">
    <input name="fileToUpload" /><br />
    <input value="Upload File" />
    </form>

    </body>
    </html>

    The Action PageOnce the user uploads a file, the file is uploaded into a temporary directory on the server. If you don't move the file it will disappear. Therefore, your action page needs to move the file to another location where it can stay as long as you want it to.
    Whenever a file is uploaded, you can find out certain information about the file including its name, type, size, as well as the name of the temporary file on the server. These details are made available to you via a PHP array called $_FILES.
    Displaying Details of the Uploaded FileThis code simply displays the details of the uploaded file. It doesn't move the file to another location - we'll get to that next. For now, you can use this code in conjunction with the above input form to demonstrate what happens when you upload a file to the server.
    Notice the PHP $_FILES array which contains info about the file. Note that we also divide the file size by 1024 in order to convert it into kb.
    (Ignore any carriage returns in this example - each table row should be on one line).
    echo "<table border=\"1\">";
    echo "<tr><td>Client Filename: </td>
    <td>" . $_FILES["fileToUpload"]["name"] . "</td></tr>";
    echo "<tr><td>File Type: </td>
    <td>" . $_FILES["fileToUpload"]["type"] . "</td></tr>";
    echo "<tr><td>File Size: </td>
    <td>" . ($_FILES["fileToUpload"]["size"] / 1024) . " Kb</td></tr>";
    echo "<tr><td>Name of Temporary File: </td>
    <td>" . $_FILES["fileToUpload"]["tmp_name"] . "</td></tr>";
    echo "</table>";

    The above code results in something like this:
    Client Filename: Water lilies.jpg File Type: image/jpeg File Size: 81.830078125 Kb Name of Temporary File: C:\WINDOWS\TEMP\php48B2.tmp Moving the Temp FileAs mentioned, if we want to keep the file on the server, we need to move it to another location (of our choice). The following code demonstrates how to move the file from the temporary location.
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
    "C:/upload/" . $_FILES["fileToUpload"]["name"]);

    Checking for ErrorsThe $_FILES array includes an item for any errors that may result from the upload. This contains an error code. If there are no errors, the value is zero ( 0 ).
    You check this value within an "If" statement. If the value is greater than zero, you know an error has occurred and you can present a user friendly message to the user. Otherwise you can processing the file.
    if ($_FILES["fileToUpload"]["error"] > 0)
    {
    echo "Apologies, an error has occurred.";
    echo "Error Code: " . $_FILES["fileToUpload"]["error"];
    }
    else
    {

    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
    "C:/upload/" . $_FILES["fileToUpload"]["name"]);
    }

    Restricting File Type/SizeLetting your users upload files to your server can be very risky. If you're not careful, you could get users uploading all sorts of files - perhaps including harmful executables etc. You could also find one day that you've run out of disk space because some users have been uploading enormous files.
    You can restrict the file types and file sizes by using an "if" statement. If the file type and size are acceptable, processing can continue, otherwise, display a message to the user.
    Important Note: This doesn't prevent the temp file from being created. The file needs uploaded to the server before PHP can find out the file size and type. This simply prevents the file from being moved to your "permanent" location - hence the file should disappear and (hopefully) not become a problem. In any case, I recommend that you install good anti-virus software before allowing users to upload files to your server.
    if (($_FILES["fileToUpload"]["type"] == "image/gif")
    || ($_FILES["fileToUpload"]["type"] == "image/jpeg")
    || ($_FILES["fileToUpload"]["type"] == "image/png" )
    && ($_FILES["fileToUpload"]["size"] < 10000))
    {
    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
    "C:/upload/" . $_FILES["fileToUpload"]["name"]);
    }
    else
    {
    echo "Files must be either JPEG, GIF, or PNG and less than 10,000 kb";
    }

      In the previous lesson we learned how to enable our users to upload files to the server. In this lesson, we'll learn how to work with files on the server.
    Reading a FileThe following code can be used to read a file.
    $file = fopen("c:/upload/myFile.txt", "r");
    while(!feof($file))
    {
    echo fgets($file). "<br />";
    }
    fclose($file);

    Here's an explanation of what's happening:
    1. Before you read a file you need to open it. We're using PHP's fopen() function and providing it with two parameters: the file name and the mode in which it should be opened.
    2. We then loop through the file using PHP's feof() function. This checks for the end of the file. Our loop specifies that, while the end of file has not been reached, process the code inside the loop.
    3. The code inside the loop uses PHP's fgets() function. This function reads the file line by line. We need to put our own break otherwise each line would end up on the same line.
    4. Finally, we close the file using PHP's fclose() function, passing the opened file as a parameter.
    Writing to a FileThe following code can be used to write to a file.
    $file = fopen("c:/upload/myFile.txt", 'w');
    fwrite($file, "File contents go here...");
    fclose($file);

    Here's an explanation of what's happening:
    1. Again, we use PHP's fopen() function and supply it with two parameters: the file name and the mode in which it should be opened.
    2. We then use PHP's fwrite() function to write to the file. We supply two parameters: the opened file, and the text to go inside the file.
    3. Finally, we close the file using PHP's fclose() function, passing the opened file as a parameter.
    Appending Data to a FileThe previous code overwrites any content that might have been in the file. If you only want to add to the end of the existing data, you can simply change the mode from "w" (for "write") to "a" (for "append").
    $file = fopen("c:/upload/myFile.txt", 'a');
    fwrite($file, "Appended file contents go here...");
    fclose($file);

    Deleting a FileTo delete a file, you use PHP's unlink() function and provide it with the name/path of the file to delete.
    unlink("c:/upload/myFile.txt");

    You can use PHP to dynamically send emails to one or more recipients. This can be handy for a lot of reasons, for example:
    • Sending newsletters to a mailing list
    • Sending a "welcome" email to new members of your website
    • A user has just made a purchase and you need to send them a receipt by email
    • Sending an email alert to your technical administrator whenever an error occurs
    • Many more reasons...
    The PHP mail() FunctionTo send email using PHP, you use the mail() function. This accepts 5 parameters as follows (the last 2 are optional)
    mail(to,subject,message,headers,parameters)

    Below is an explanation of the parameters.
    Parameter Description to Required. The recipient's email address. subject Required. The email's subject line. message Required. The actual email body. headers Optional. Additional header fields such as "From", "Cc", "Bcc" etc. parameters Optional. Any additional parameters. Sending an EmailYou could send email by simply doing this:
    mail("[email protected]",
    "Thank you for registering!",
    "Hello Homer, thank you for registering!",
    "From: [email protected]");

    Although, in reality, you would probably set your parameters up as variables. Also, if the email was triggered by a user, you would probably provide them with feedback to say that the email had been sent.
    // Set up parameters
    $to = "[email protected]";
    $subject = "Your password";
    $message = "Hello Homer, thanks for registering. Your password is: springfield";
    $from = "[email protected]";
    $headers = "From: $from";

    // Send email
    mail($to,$subject,$message,$headers);

    // Inform the user
    echo "Thanks for registering! We have just sent you an email with your password.";

    HTML EmailsTo send an HTML email, the process is the same, however, you need to provide additional headers (as well as an HTML formatted message).
    Note that you need to separate each header with a carriage return.
    For Windows systems, use this code:
    // Set up parameters
    $to = "[email protected]";
    $subject = "Your password";
    $message = "<p>Hello Homer,</p>
    <p>Thanks for registering.</p>
    <p>Your password is: <b>springfield</b></p>
    ";

    $from = "[email protected]";
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
    $headers .= "From: $from" . "\r\n";


    // Send email
    mail($to,$subject,$message,$headers);

    // Inform the user
    echo "Thanks for registering! We have just sent you an email with your password.";

    For UNIX systems, use this code:
    // Set up parameters
    $to = "[email protected]";
    $subject = "Your password";
    $message = "<p>Hello Homer,</p>
    <p>Thanks for registering.</p>
    <p>Your password is: <b>springfield</b></p>
    ";

    $from = "[email protected]";
    $headers = "MIME-Version: 1.0" . "\n";
    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\n";
    $headers .= "From: $from" . "\n";


    // Send email
    mail($to,$subject,$message,$headers);

    // Inform the user
    echo "Thanks for registering! We have just sent you an email with your password.";

    Difference Between UNIX and Windows Code?You probably noticed in the above example that there's a Windows version and a UNIX version.
    The only difference is in the way the carriage returns are specified. On Windows it's "\r\n", on UNIX it's "\n".
    The PHP specification stipulates that you should use "\r\n" for creating the carriage returns. This should work fine on Windows systems. UNIX systems however, have a tendency to add "\r" to the "\n", therefore resulting in "r\r\n", which of course, wouldn't work. Therefore, we simply leave out the "\r" on the UNIX version.
    Configuring Mail on PHPThe above steps assume that your PHP installation is configured to send mail. Your hosting provider should already have configured PHP to send mail, so you shouldn't need to do anything further if your website is hosted with a third party hosting provider.
    If you need to send mail from your local computer, you may need to configure PHP to send mail. The next lesson explains this.
 In the previous lesson, we used mail() to send mail in PHP. That lesson assumes that your PHP installation is configured for sending mail. If your system isn't configured for sending mail, all is not lost - you can change the configuration. This lesson explains how to configure PHP for sending mail.
The php.ini FileThe php.ini file is where you configure your PHP installation. This is the file you need to edit in order to configure PHP to send mail.
You need to ensure that the php.ini file contains details of the mail server that should be used whenever your application sends mail.
To check/change your PHP mail configuration:
  1. Open your php.ini file (if you don't know where this is, see below)
  2. Search for the line that reads [mail function]
  3. Add/change the details of your mail server. This could be a local mail server or the mail server of your ISP.
  4. Save/close the php.ini file
  5. Restart your web server
Here's an example of what the mail settings could look like when you first open the php.ini file:
[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = [email protected]

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =

If you're using a UNIX based system, you will need to change the line that reads ;sendmail_path =. You will also need to remove the semicolon from the start of this line (semicolons indicate that the line is a comment). For example, sendmail_path = /usr/sbin/sendmail.
If you're using a Windows system, you should change the line that reads SMTP = localhost to include your mail server (or your ISP's mail server). You could leave it at localhost if you're using your own local SMTP server. If you aren't using your own local SMTP server, you will need to enter a mail server that you have access to (such as your ISP's mail server). For example, SMTP = mail.earthlink.net.
You should also set a default "From" email address by changing the line that reads ;sendmail_from = [email protected]. For example, sendmail_from = [email protected].
Don't Know Your php.ini Location or sendmail_path Path?If you don't know where your php.ini is, or what your sendmail_path setting should be, read on...
Your php.ini may be located here: /private/etc/php.ini. And there's a chance that your sendmail path will be at /usr/sbin/sendmail). Having said this, each PHP installation is different, so you should check using phpinfo().
Fortunately, this is easy to do.
phpinfo() is used to view your PHP configuration details. You can do this by creating a .php file with the following line on it: <?php phpinfo(); ?>. When you run this in your browser, you will see a full list of PHP configuration variables. Simply search for the lines that contain php.ini and sendmail_path to see the values you need to use.

You can use PHP, (in conjunction with SQL and HTML), to create database driven websites.
To create a database driven website in PHP, you need a database management system (DBMS). Common database systems include MySQL, Microsoft SQL Server, and Oracle.
Your DBMS can be located either on the same computer that the website is on, or on another server. It's good practice to separate your database server from your web server, but if you've only got one machine to develop on, sharing the same machine shouldn't cause any problems (as long as it's powerful enough to run a web server and database server etc).
Anyway, once you have a database with some tables and some data, you can connect to it and query it.
MySQL is a database system commonly used with PHP websites. The following examples demonstrate how to connect and query a MySQL database.
Connecting to the DatabaseBefore you can query your database, you need to connect to the database server, then locate the database. Once you've done this, you can send in your SQL code to do your queries.
To connect to the database server:
mysql_connect("localhost", "web_user", "LetMeIn!") or die(mysql_error());

The above code uses the mysql_connect function to connect to the database server. We provide the following parameters: Server, Username, Password. PHP needs this info so that it knows which server to connect to. In this example we are just connecting to the local machine so we use "localhost" as the server.
We have also used the PHP die and mysql_error functions to be used in the event there's an error and PHP can't connect to the server. This will display the error message which can assist us in determining the cause of the problem.
To select the database:
mysql_select_db("MyDatabase") or die(mysql_error());

The above code uses the mysql_select_db function to select the database from the database server. You need to do this because, your database server could contain many databases. You need to tell PHP which database to use.
Again we use the die and mysql_error functions to be used in the event of an error.
Querying the DatabaseYou can use the mysql_query function to send a SQL query to the database:
$result = mysql_query("SELECT * FROM Individual")
or die(mysql_error());

What we do here is, assign the results of a query to the $result variable. The query is acheived by passing a SQL statement to the mysql_query as a parameter. In this SQL statement, we are selecting all records from the "Individual" table.
Once again we use the die and mysql_error in case there's an error.
Displaying the ResultsTo display the results, you need to loop through the results of the query and display each record with each iteration of the loop:
while($row = mysql_fetch_array($result)){
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}

Here we use a while loop to loop through the results of the query. The while loop keeps iterating until it finishes the last result. This means we can display each result as it iterates past that result. We display the result using $echo and the PHP $row variable, indicating which columns we want to display.
The Whole CodeCombining the above code, (and adding comments), results in something like this:
<?php
// Connect to the database server
mysql_connect("localhost", "web_user", "LetMeIn!") or die(mysql_error());

// Open to the database
mysql_select_db("MyDatabase") or die(mysql_error());

// Select all records from the "Individual" table
$result = mysql_query("SELECT * FROM Individual")
or die(mysql_error());

// Loop thru each record (using the PHP $row variable),
// then display the first name and last name of each record.
while($row = mysql_fetch_array($result)){
echo $row['FirstName']. " - ". $row['LastName'];
echo "<br />";
}
?>


Congratulations! You've reached the end of this tutorial.
You should now be able to create some very functional, dynamic websites using PHP as a server side language. There is still much more to PHP though, so I encourage you to keep learning.
What Next?Now that you've seen what is involved in PHP programming, you might like to compare PHP with another server side language. Try the ColdFusion Tutorial and you'll see that many concepts are the same between different languages.
You may find yourself in the situation where you need to create a database driven website. In that case, you'll need to know about databases. Also, to query your databases, you need to know SQL.
And, I did say at the beginning of this tutorial that you should have experience with HTML before continuing with the tutorial. If you chose to ignore me, and you still understood this tutorial - well done! In any case, now would be a great time to learn HTML!.