A PHP file normally contains HTML
tags, just like an HTML file, and some PHP scripting code.
Below, we have an example of a
simple PHP script which sends the text "Hello World" to the browser:
<html> <body> <?php echo "Hello World"; ?> </body> </html> |
A PHP scripting block always
starts with <?php and ends with ?>. A PHP scripting block
can be placed anywhere in the document.
Each code line in PHP must end
with a semicolon. The semicolon is a separator and is used to distinguish one
set of instructions from another.
There are two basic statements to
output text with PHP: echo and print. In the example above we
have used the echo statement to output the text "Hello World".
All variables in PHP start with a
$ sign symbol. Variables may contain strings, numbers, or arrays.
Below, the PHP script assigns the
string "Hello World" to a variable called $txt:
<html> <body> <?php $txt="Hello World"; echo $txt; ?> </body> </html> |
To concatenate two or more
variables together, use the dot (.) operator:
<html> <body> <?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2 ; ?> </body> </html> |
The output of the script above
will be: "Hello World 1234".
In PHP, we use // to make a
single-line comment or /* and */ to make a large comment block.
<html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html> |
Operators are used to operate on
values.
This section lists the different
operators used in PHP.
Arithmetic Operators
Operator |
Description |
Example |
Result |
+ |
Addition |
x=2 |
4 |
- |
Subtraction |
x=2 |
3 |
* |
Multiplication |
x=4 |
20 |
/ |
Division |
15/5 |
3 |
% |
Modulus (division remainder) |
5%2 |
1 |
++ |
Increment |
x=5 |
x=6 |
-- |
Decrement |
x=5 |
x=4 |
Assignment Operators
Operator |
Example |
Is The Same As |
= |
x=y |
x=y |
+= |
x+=y |
x=x+y |
-= |
x-=y |
x=x-y |
*= |
x*=y |
x=x*y |
/= |
x/=y |
x=x/y |
%= |
x%=y |
x=x%y |
Comparison Operators
Operator |
Description |
Example |
== |
is equal to |
5==8 returns false |
!= |
is not equal |
5!=8 returns true |
> |
is greater than |
5>8 returns false |
< |
is less than |
5<8 returns true |
>= |
is greater than or equal to |
5>=8 returns false |
<= |
is less than or equal to |
5<=8 returns true |
Logical Operators
Operator |
Description |
Example |
&& |
and |
x=6 (x < 10 && y > 1)
returns true |
|| |
or |
x=6 (x==5 || y==5) returns false |
! |
not |
x=6 !(x==y) returns true |
Conditional statements in PHP are
used to perform different actions based on different conditions.
Very often when you write code,
you want to perform different actions for different decisions. You can use
conditional statements in your code to do this.
In PHP we have two conditional
statements:
If you want to execute some code
if a condition is true and another code if a condition is false, use the
if....else statement.
if (condition) code to be executed if condition is true; else code to be executed if condition is false; |
The following example will output
"Have a nice weekend!" if the current day is Friday, otherwise it
will output "Have a nice day!":
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html> |
If more than one line should be
executed when a condition is true, the lines should be enclosed within curly
braces:
<html> <body> <?php $x=10; if ($x==10) { echo "Hello<br />"; echo "Good morning<br />"; } ?> </body> </html> |
If you want to select one of many
blocks of code to be executed, use the Switch statement.
switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } |
This is how it works: First we
have a single expression (most often a variable), that is evaluated once. The
value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case
automatically. The default statement is used if none of the cases are true.
<html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html> |
Looping statements in PHP are used
to execute the same block of code a specified number of times.
Very often when you write code,
you want the same block of code to run a number of times. You can use looping
statements in your code to perform this.
In PHP we have the following
looping statements:
The while statement will execute a
block of code if and as long as a condition is true.
while (condition) code to be executed; |
The following example demonstrates
a loop that will continue to run as long as the variable i is less than, or
equal to 5. i will increase by 1 each time the loop runs:
<html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> |
The do...while statement will
execute a block of code at least once - it then will repeat the loop as
long as a condition is true.
do { code to be executed; } while (condition); |
The following example will
increment the value of i at least once, and it will continue incrementing the
variable i while it has a value of less than 5:
<html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html> |
The for statement is used when you
know how many times you want to execute a statement or a list of statements.
for (initialization; condition; increment) { code to be executed; } |
Note: The for statement has three parameters.
The first parameter is for initializing variables, the second parameter holds
the condition, and the third parameter contains any increments required to
implement the loop. If more than one variable is included in either the
initialization or the increment section, then they should be separated by
commas. The condition must evaluate to true or false.
The following example prints the
text "Hello World!" five times:
<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html> |
Loops over the array given by the
parameter. On each loop, the value of the current element is assigned to $value
and the array pointer is advanced by one - so on the next loop, you'll be
looking at the next element.
foreach (array as value) { code to be executed; } |
The following example demonstrates
a loop that will print the values of the given array:
<html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html> |
The real power of PHP comes from
its functions.
In PHP - there are more than 700
functions available.
We will only list a few useful
functions in this tutorial.
A complete list of PHP
functions
The phpinfo() function is used to
output PHP information.
This function is useful for
trouble shooting, providing the version of PHP, and how it is configured.
Name |
Description |
INFO_GENERAL |
The configuration line, php.ini location, build date, Web
Server, System and more |
INFO_CREDITS |
PHP 4 credits |
INFO_CONFIGURATION |
Local and master values for php directives |
INFO_MODULES |
Loaded modules |
INFO_ENVIRONMENT |
Environment variable information |
INFO_VARIABLES |
All predefined variables from EGPCS (Environment, GET, POST,
Cookie, Server) |
INFO_LICENSE |
PHP license information |
INFO_ALL |
Shows all of the above. This is the default value |
<html> <body> <?php // Show all PHP information phpinfo(); ?> <?php // Show only the general information phpinfo(INFO_GENERAL); ?> </body> </html> |
All servers hold information such
as which URL the user came from, what's the user's browser, and other
information. This information is stored in variables.
In PHP, the $_SERVER is a reserved
variable that contains all server information. The $_SERVER is a global
variable - which means that it's available in all scopes of a PHP script.
The following example will output
which URL the user came from, the user's browser, and the user's IP address:
<html> <body> <?php echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />"; echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />"; echo "User's IP address: " . $_SERVER["REMOTE_ADDR"]; ?> </body> </html> |
The header() function is used to
send raw HTTP headers over the HTTP protocol.
Note: This function must be called before
anything is written to the page!
The following example will
redirect the browser to the following URL: http://www.w3schools.com/:
<?php //Redirect browser header("Location: http://www.w3schools.com/"); ?> <html> <body> ...... </body> </html> |
Note: This function also takes a second
parameter - an optional value of true or false to determine if the header
should replace the previous header. Default is TRUE.
However, if you pass in FALSE as
the second argument you can FORCE multiple headers of the same type.
<?php header("WWW-Authenticate: Negotiate"); header("WWW-Authenticate: NTLM", FALSE); ?> <html> <body> ...... </body> </html> |
This section describes file
handling in PHP.
The fopen() function is used to
open files in PHP.
The first parameter of this
function contains the name of the file to be opened and the second parameter
specifies in which mode the file should be opened in:
<html> <body> <?php $f=fopen("welcome.txt","r"); ?> </body> </html> |
The file may be opened in one of
the following modes:
File Modes |
Description |
r |
Read only. File pointer at the start of the file |
r+ |
Read/Write. File pointer at the start of the file |
w |
Write only. Truncates the file (overwriting it). If the file
doesn't exist, fopen() will try to create the file |
w+ |
Read/Write. Truncates the file (overwriting it). If the file
doesn't exist, fopen() will try to create the file |
a |
Append. File pointer at the end of the file. If the file doesn't
exist, fopen() will try to create the file |
a+ |
Read/Append. File pointer at the end of the file. If the file
doesn't exist, fopen() will try to create the file |
x |
Create and open for write only. File pointer at the beginning of
the file. If the file already exists, the fopen() call will fail and generate
an error. If the file does not exist, try to create it |
x+ |
Create and open for read/write. File pointer at the beginning of
the file. If the file already exists, the fopen() call will fail and generate
an error. If the file does not exist, try to create it |
Note: If the fopen() function is unable to open
the specified file, it returns 0 (false).
The following example generates a
message if the fopen() function is unable to open the specified file:
<html> <body> <?php if (!($f=fopen("welcome.txt","r"))) exit("Unable to open file!"); </body> </html> |
The fclose() function is used to
close a file.
fclose($f); |
The feof() function is used to
determine if the end of file is true.
Note: You cannot read from files opened in w, a,
and x mode!
if (feof($f)) echo "End of file"; |
The fgetc() function is used to
read a single character from a file.
Note: After a call to this function the file
pointer has moved to the next character.
The example below reads a file
character by character, until the end of file is true:
<?php if (!($f=fopen("welcome.txt","r"))) exit("Unable to open file."); while (!feof($f)) { $x=fgetc($f); echo $x; } fclose($f); ?> |
A very powerful feature of PHP is
the way it handles HTML forms!
The most important thing to notice
when dealing with HTML forms and PHP is that any form element in an HTML page
will automatically be available to your PHP scripts.
Look at the following example of
an HTML form:
<html> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> |
The example HTML page above
contains two input fields and a submit button. When the user fills in this form
and hits the submit button, the "welcome.php" file is called.
The "welcome.php" file
looks like this:
<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! </body> </html> |
A sample output of the above
script may be:
Welcome John. You are 28 years old! |
Here is how it works: The
$_POST["name"] and $_POST["age"] variables are
automatically set for you by PHP. The $_POST contains all POST data.
Note: If the method attribute of the form is
GET, then the form information will be set in $_GET instead of $_POST.
A cookie is often used to identify
a user.
A cookie is often used to identify
a user. A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests for a page with a browser, it will send
the cookie too. With PHP, you can both create and retrieve cookie values.
The setcookie() function is used
to create cookies.
Note: The setcookie() function must appear
BEFORE the <html> tag.
setcookie(name, value, expire, path, domain); |
The following example sets a
cookie named "uname" - that expires after ten hours.
<?php setcookie("uname", $name, time()+36000); ?> <html> <body> <p> A cookie was set on this page! The cookie will be active when the client has sent the cookie back to the server. </p> </body> </html> |
When a cookie is set, PHP uses the
cookie name as a variable.
To access a cookie you just refer
to the cookie name as a variable.
Tip: Use the isset() function to find out if a
cookie has been set.
The following example tests if the
uname cookie has been set, and prints an appropriate message.
<html> <body> <?php if (isset($_COOKIE["uname"])) echo "Welcome " . $_COOKIE["uname"] . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html> |
Server Side Includes (SSI) are
used to create functions, headers, footers, or elements that will be reused on
multiple pages.
You can insert the content of one
file into another file before the server executes it, with the require()
function. The require() function is used to create functions, headers, footers,
or elements that will be reused on multiple pages.
This can save the developer a
considerable amount of time. If all of the pages on your site have a similar
header, you can include a single file containing the header into your pages.
When the header needs updating, you only update the one page, which is included
in all of the pages that use the header.
The following example includes a
header that should be used on all pages:
<html> <body> <?php require("header.htm"); ?> <p> Some text </p> <p> Some text </p> </body> </html> |