Monday, September 19, 2011

Using PHP With HTML Forms

It is time to apply the knowledge you have obtained thus far and put it to real use. A very common application of PHP is to have an HTML form gather information from a website's visitor and then use PHP to do process that information. In this lesson we will simulate a small business's website that is implementing a very simple order form.
Imagine we are an art supply store that sells brushes, paint, and erasers. To gather order information from our prospective customers we will have to make a page with an HTML form to gather the customer's order.
Note: This is an oversimplified example to educate you how to use PHP to process HTML form information. This example is not intended nor advised to be used on a real business website.


If you need a refresher on how to properly make an HTML form, check out the HTML Form Lesson before continuing on.
We first create an HTML form that will let our customer choose what they would like to purchase. This file should be saved as "order.html"


order.html Code:
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form>
<select>
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input type="text" />
<input type="submit" />
</form>
</body></html>


PHP Form Processor


We want to get the "item" and "quantity" inputs that we have specified in our HTML form. Using an associate array (this term is explained in the array lesson), we can get this information from the $_POST associative array.
The proper way to get this information would be to create two new variables, $item and $quantity and set them equal to the values that have been "posted". The name of this file is "process.php".
process.php Code:
<html><body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?>
</body></html>
As you probably noticed, the name in $_POST['name'] corresponds to the name that we specified in our HTML form.
Now try uploading the "order.html" and "process.php" files to a PHP enabled server and test them out. If someone selected the item brushes and specified a quantity of 6, then the following would be displayed on "process.php":


Remember to review HTML Forms if you do not understand any of the above HTML code. Next we must alter our HTML form to specify the PHP page we wish to send this information to. Also, we set the method to "post".


PHP & HTML Form Review

A lot of things were going on in this example. Let us step through it to be sure you understand what was going on.
1. We first created an HTML form "order.html" that had two input fields specified, "item" and "quantity".
2. We added two attributes to the form tag to point to "process.php" and set the method to "post".
3. We had "process.php" get the information that was posted by setting new variables equal to the values in the $_POST associative array.
4. We used the PHP echo function to output the customers order.
Remember, this lesson is only to teach you how to use PHP to get information from HTML forms. The example on this page should not be used for a real business.



PHP Switch Statement


In the previous lessons we covered the various elements that make up an If Statement in PHP. However, there are times when an if statement is not the most efficient way to check for certain conditions.
For example we might have a variable that stores travel destinations and you want to pack according to this destination variable. In this example you might have 20 different locations that you would have to check with a nasty long block of If/ElseIf/ElseIf/ElseIf/... statements. This doesn't sound like much fun to code, let's see if we can do something different.

PHP Switch Statement: Speedy Checking

With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation!
The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.

PHP Switch Statement Example


In our example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam, Egypt, Tokyo, and the Caribbean Islands.

PHP Code:
$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
}
Display:
Traveling to Tokyo
 Bring lots of money

The value of $destination was Tokyo, so when PHP performed the switch operating on $destination in immediately did a search for a case with the value of "Tokyo". It found it and proceeded to execute the code that existed within that segment.
You might have noticed how each case contains a break; at the end of its code area. This break prevents the other cases from being executed. If the above example did not have any break statements then all the cases that follow Tokyo would have been executed as well. Use this knowledge to enhance the power of your switch statements!
The form of the switch statement is rather unique, so spend some time reviewing it before moving on. Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.

PHP Switch Statement: Default Case


You may have noticed the lack of a place for code when the variable doesn't match our condition. The if statement has the else clause and the switch statement has the default case.
It's usually a good idea to always include the default case in all your switch statements. Below is a variation of our example that will result in none of the cases being used causing our switch statement to fall back and use the default case. Note: there is no case before default.

PHP Code:
$destination = "New York";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
default:
echo "Bring lots of underwear!";
break;
}

Display:
Traveling to New York Bring lots of underwear!

The If Statement

The PHP if statement is very similar to other programming languages use of the if statement, but for those who are not familiar with it, picture the following:
Think about the decisions you make before you go to sleep. If you have something to do the next day, say go to work, school, or an appointment, then you will set your alarm clock to wake you up. Otherwise, you will sleep in as long as you like!
This simple kind of if/then statement is very common in every day life and also appears in programming quite often. Whenever you want to make a decision given that something is true (you have something to do tomorrow) and be sure that you take the appropriate action, you are using an if/then relationship.

The PHP If Statement


The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.
This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.

If Statement Example


The "Happy New Year" example would be a little difficult for you to do right now, so let us instead start off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement.

PHP Code:
$my_name = "someguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";
Display:
Your name is someguy! Welcome to my homepage!

Did you get that we were comparing the variable $my_name with "someguy" to see if they were equal? In PHP you use the double equal sign (==) to compare values. Additionally, notice that because the if statement turned out to be true, the code segment was executed, printing out "Your name is someguy!". Let's go a bit more in-depth into this example to iron out the details.
• We first set the variable $my_name equal to "someguy".
• We next used a PHP if statement to check if the value contained in the variable $my_name was equal to "someguy"
• The comparison between $my_name and "someguy" was done with a double equal sign "==", not a single equals"="! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal.
• Translated into english the PHP statement ( $my_name == "someguy" ) is ( $my_name is equal to "someguy" ).
• $my_name is indeed equal to "someguy" so the echo statement is executed.

A False If Statement


Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to:

PHP Code:
$my_name = "anotherguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";
Display:
Welcome to my homepage!

Here the variable contained the value "anotherguy", which is not equal to "someguy". The if statement evaluated to false, so the code segment of the if statement was not executed. When used properly, the if statement is a powerful tool to have in your programming arsenal!

If/Else Conditional Statement

Has someone ever told you, "if you work hard, then you will succeed"? And what happens if you do not work hard? Well, you fail! This is an example of an if/else conditional statement.
• If you work hard then you will succeed.
• Else, if you do not work hard, then you will fail.
How does this translate into something useful for PHP developers? Well consider this:
Someone comes to your website and you want to ask this visitor her name if it is her first time coming to your site. With an if statement this is easy. Simply have a conditional statement to check, "are you visiting for the first time". If the condition is true, then take them to the "Insert Your Name" page, else let her view the website as normal because you have already asked her for her name in the past.

If/Else an Example


Using these conditional statements can add a new layers of "cool" to your website. Here's the basic form of an if/else statement in PHP.

PHP Code:
$number_three = 3;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}
Display:
The if statement evaluated to

Friday, September 16, 2011

PHP Operators


PHP - Operators



In all programming languages, operators are used to manipulate or perform operations on variables and values. You have already seen the string concatenation operator "." in the Echo Lesson and the assignment operator "=" in pretty much every PHP example so far.
There are many operators used in PHP, so we have separated them into the following categories to make it easier to learn them all.
• Assignment Operators
• Arithmetic Operators
• Comparison Operators
• String Operators
• Combination Arithmetic & Assignment Operators

Assignment Operators
Assignment operators are used to set a variable equal to a value or set a variable to another variable's value. Such an assignment of value is done with the "=", or equal character. Example:
• $my_var = 4;
• $another_var = $my_var
Now both $my_var and $another_var contain the value 4. Assignments can also be used in conjunction with arithmetic operators.

Arithmetic Operators


Operator      English                     Example
+                 Addition                   2 + 4
-                 Subtraction                6 - 2
*                Multiplication             5 * 3
/                 Division                     15 / 3
%              Modulus                     43 % 10

PHP Code:
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiplication = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo "Perform addition: 2 + 4 = ".$addition."<br />";
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />";
echo "Perform multiplication: 5 * 3 = ".$multiplication."<br />";
echo "Perform division: 15 / 3 = ".$division."<br />";
echo "Perform modulus: 5 % 2 = " . $modulus
. ". Modulus is the remainder after the division operation has been performed.
In this case it was 5 / 2, which has a remainder of 1.";
Display:
Perform addition: 2 + 4 = 6
Perform subtraction: 6 - 2 = 4
Perform multiplication: 5 * 3 = 15
Perform division: 15 / 3 = 5
Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed. In this case it was 5 / 2, which has a remainder of 1.

Comparison Operators


Comparisons are used to check the relationship between variables and/or values. If you would like to see a simple example of a comparison operator in action, check out our If Statement Lesson. Comparison operators are used inside conditional statements and evaluate to either true or false. Here are the most important comparison operators of PHP. Assume: $x = 4 and $y = 5;
Operator         English                                Example          Result
==                  Equal To                             $x == $y         false
!=                   Not Equal To                      $x != $y          true
<                    Less Than                           $x < $y            true
>                   Greater Than                       $x > $y             false
<=                 Less Than or Equal To         $x <= $y          true
>=                Greater Than or Equal To     $x >= $y           false

String Operators


As we have already seen in the Echo Lesson, the period "." is used to add two strings together, or more technically, the period is the concatenation operator for strings.
PHP Code:
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";
Display:
Hello Billy!

Combination Arithmetic & Assignment Operators


In programming it is a very common task to have to increment a variable by some fixed amount. The most common example of this is a counter. Say you want to increment a counter by 1, you would have:
• $counter = $counter + 1;
However, there is a shorthand for doing this.
• $counter += 1;
This combination assignment/arithmetic operator would accomplish the same task. The downside to this combination operator is that it reduces code readability to those programmers who are not used to such an operator. Here are some examples of other common shorthand operators. In general, "+=" and "-=" are the most widely used combination operators.
Operator          English                   Example                    Equivalent Operation
+=Plus              Equals                      $x += 2;                     $x = $x + 2;
-=                     Minus Equals            $x -= 4;                     $x = $x - 4;
*=                    Multiply Equals         $x *= 3;                     $x = $x * 3;
/=                     Divide Equals            $x /= 2;                      $x = $x / 2;
%=                  Modulo Equals           $x %= 5;                   $x = $x % 5;
.=                   Concatenate Equals     $my_str.="hello";       $my_str = $my_str . "hello";

Pre/Post-Increment & Pre/Post-Decrement


This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or subtracting 1 from a variable. To add one to a variable or "increment" use the "++" operator:
• $x++; Which is equivalent to $x += 1; or $x = $x + 1;

To subtract 1 from a variable, or "decrement" use the "--" operator:

• $x--; Which is equivalent to $x -= 1; or $x = $x - 1;
In addition to this "shorterhand" technique, you can specify whether you want the increment to before the line of code is being executed or after the line has executed. Our PHP code below will display the difference.
PHP Code:
$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;
Display:
The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5

As you can see the value of $x++ is not reflected in the echoed text because the variable is not incremented until after the line of code is executed. However, with the pre-increment "++$x" the variable does reflect the addition immediately.

PHP Echo


PHP - Echo
As you saw in the previous lesson, the PHP function echo is a means of outputting text to the web browser. Throughout your PHP career you will be using the echo function more than any other. So let's give it a solid perusal!
Outputting a String
To output a string, like we have done in previous lessons, use the PHP echo function. You can place either a string variable or you can use quotes, like we do below, to create a string that the echo function will output.
PHP Code:
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>
Display:
Hello!

I love using PHP!
In the above example we output "Hello!" without a hitch. The text we are outputting is being sent to the user in the form of a web page, so it is important that we use proper HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this we simply put the <h5> at the beginning of the string and closed it at the end of the string. Just because you're using PHP to make web pages does not mean you can forget about HTML syntax!
Careful When Echoing Quotes!
It is pretty cool that you can output HTML with PHP. However, you must be careful when using HTML code or any other string that includes quotes! The echo function uses quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations:
• Don't use quotes inside your string
• Escape your quotes that are within the string with a slash. To escape a quote just place a slash directly before the quotation mark, i.e. \"
• Use single quotes (apostrophes) for quotes inside your string.
See our example below for the right and wrong use of the echo function:
PHP Code:
<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";
// OK because we escaped the quotes!
echo "<h5 class=\"specialH5\">I love using PHP!</h5>";
// OK because we used an apostrophe '
echo "<h5 class='specialH5'>I love using PHP!</h5>";
?>
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the quotations by placing a slash in front of it ( \" ). The slash will tell PHP that you want the quotation to be used within the string and NOT to be used to end echo's string.
Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the common task of echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold a string. Below is the correct format for echoing a variable.
PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>
Display:
Hello Bob. My name is: 4a

Echoing Variables and Text Strings
You can also combine text strings and variables. By doing such a conjunction you save yourself from having to do a large number of echo statements. Variables and text strings are joined together with a period( . ). The example below shows how to do such a combination.
PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
$newline = "<br />";
echo $my_string."Bobettta".$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string.$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string."Bobetta";
?>
Display:
Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta

This combination can be done multiple times, as the example shows. This method of joining two or more strings together is called concatenation and we will talk more about this and other forms of string manipulation in our string lesson.

PHP Variables


PHP - Variables


If you have never had any programming, Algebra, or scripting experience, then the concept of variables might be a new concept to you. A detailed explanation of variables is beyond the scope of this tutorial, but we've included a refresher crash course to guide you.
A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
• $variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!

A Quick Variable Example


Say that we wanted to store the values that we talked about in the above paragraph. How would we go about doing this? We would first want to make a variable name and then set that equal to the value we want. See our example below for the correct way to do this.
PHP Code:
<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Note for programmers: PHP does not require variables to be declared before being initialized.

PHP Variable Naming Conventions


There are a few rules that you need to follow when choosing a name for your PHP variables.
• PHP variables must start with a letter or underscore "_".
• PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
• Variables with more than one word should be separated with underscores. $my_variable
• Variables with more than one word can also be distinguished with capitalization. $myVariable

Thursday, September 15, 2011

Printing Date and PHP Date Formats

<html>

<head>
<title>Example #1 Very First PHP Script ever!</title>
</head>
<? print(Date("1 F d, Y")); ?>
<body>
</body>
</html>


This sample code for printing date in php.

Date Function Formatting


DAYS
d - day of the month 2 digits (01-31)
j - day of the month (1-31)
D - 3 letter day (Mon - Sun)
l - full name of day (Monday - Sunday)
N - 1=Monday, 2=Tuesday, etc (1-7)
S - suffix for date (st, nd, rd)
w - 0=Sunday, 1=Monday (0-6)
z - day of the year (1=365)
WEEK
W - week of the year (1-52)
MONTH
F - Full name of month (January - December)
m - 2 digit month number (01-12)
n - month number (1-12)
M - 3 letter month (Jan - Dec)
t - Days in the month (28-31)
YEAR
L - leap year (0 no, 1 yes)
o - ISO-8601 year number (Ex. 1979, 2006)
Y - four digit year (Ex. 1979, 2006)
y - two digit year (Ex. 79, 06)
TIME
a - am or pm
A - AM or PM
B - Swatch Internet time (000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-23)
i - 2 digit minutes (00-59)
s - 2 digit seconds (00-59)
OTHER e - timezone (Ex: GMT, CST)
I - daylight savings (1=yes, 0=no)
O - offset GMT (Ex: 0200)
Z - offset in seconds (-43200 - 43200)
r - full RFC 2822 formatted date

Your first PHP-enabled page

Example #1 Our first PHP script: hello.php
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'?>
 </body>
</html>
Use your browser to access the file with your web server's URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.
The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.
Note: A Note on Line Feeds
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.
Note: A Note on Text Editors
There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
Note: A Note on Word Processors
Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
Note: A Note on Windows Notepad
If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.
Example #2 Get system information from PHP
<?php phpinfo(); ?>

Wednesday, September 14, 2011

What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming (OOP), or a mixture of them both.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects.

PHP has useful text processing features, which includes the Perl compatible regular expressions (PCRE), and many extensions and tools to parse and access XML documents. PHP standardizes all of the XML extensions on the solid base of libxml2, and extends the feature set adding SimpleXML, XMLReader and XMLWriter support.

And many other interesting extensions exist, which are categorized both alphabetically and by category. And there are additional PECL extensions that may or may not be documented within the PHP manual itself, like » XDebug.

As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.

What is PHP?


PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
Nice, but what does that mean? An example:
Example #1 An introductory example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <?php
            
echo "Hi, I'm a PHP script!";
        
?>
    </body>
</html>

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."
What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.
Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.    

PHP Manual

PHP Manual

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

This manual consists primarily of a function reference, but also contains a language reference, explanations of some of PHP's major features, and other supplemental information.

You can download this manual in several formats at » http://www.php.net/download-docs.php. More information about how this manual is developed can be found in the 'About the manual' appendix. If you are interested in the history of PHP, visit the relevant appendix.
Authors and Contributors

We highlight the currently most active people on front page of the manual, but there are many more contributors who currently help in our work or have provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All of the lists provided below are in alphabetical order.