Professional Documents
Culture Documents
PHP stands for Hypertext Preprocessor and is a server-side language. This means that when a visitor opens
the page, the server processes the PHP commands and then sends the results to the visitor's browser, just as
with ASP. A typical PHP files will content commands to be executed in the server in addition to the usual
mixture of text and HTML (Hypertext Markup Language) tags. However, PHP is Open Source and crossplatform. PHP runs on Windows NT and many Unix versions, and it can be built as an Apache module and
as a binary that can run as a CGI.
When you type an URL in the Address box or click a link on a Web page, you're asking a Web server on a
computer somewhere to send a file to the Web browser on your computer. If that file is a normal HTML file,
it looks exactly the same when your Web browser receives it as it did before the Web server sent it. After
receiving the file, your Web browser displays its contents as a combination of text, images, and sounds. In
the case of a PHP page, the process is similar, except there's an extra processing step that takes place just
before the Web server sends the file. Before the Web server sends the PHP file to the Web browser, it runs all
server-side scripts contained in the page.
PHP Syntax
PHP's language syntax is similar to C's and Perl's. You don't have to declare variables before you use them,
and it's easy to create arrays and hashes (associative arrays). PHP even has some rudimentary objectoriented features, providing a helpful way to organize and encapsulate your code. Beyond its basic syntax,
PHP also boasts a wide range of interfaces allowing it to communicate with everything from other web
pages, to databases including ODBC, and other programming languages such as Java or COM. PHP goes
right into your Web pages, so there's no need for a special development environment or IDE. You start a
block of PHP code with <?php and end it with ?>.
PHP is appropriate whenever you want your pages to be created dynamically when the browser
requests the page. For example, you can display date, time, and other information in different ways.
PHP will make your website more dynamic in content and a heck of a lot easier to update.
PHP makes it easy to customize a Web page to make it more useful for individual users.
With PHP you can set cookies, manage authentication, and redirect users.
One of PHP most powerful features is database access. With PHP it is possible to access over 19
different types of databases and manipulate data within those databases based on input from the user
via a web page.
Do you have a guestbook on your web site? Do you subscribe to a third-party service that provides
statistics on site visitors? Would you like to know how a user got into your web page, where they
visited on your web site, and what page they left from? With PHP, such tasks are almost trivial.
PHP makes it easy to send e-mail, work with newsgroups, and actually open a connection to another
web site -- and get or send data with it. If you are already familiar with ASP development, PHP can
also communicate with other server-side languages such as Java and use COM interfaces.
PHP provides the means to do everything from generating PDF documents to parsing XML.
This is only a small part of possibilities that PHP provides you with. Read WebCheatSheet articles devoted
to PHP to learn how to make exciting, dynamic, easy to update webpages using PHP.
It is assumed that you have already successfully setup IIS or installed Apache on your machine and
configured it. So, to configure PHP and secure its correct operation you need to go through a couple of steps.
1.
Either add "C:\PHP;" to the beginning or ";C:\PHP" to the end (sans quotes, not both).
(To restart IIS you should right-click the local computer in the left pane of IIS Manager, click on All Tasks
-> Restart IIS... -> OK)
Instead, you can copy all non-php dll files from C:\PHP to C:\Windows\System32 (or somewhere else in the
server's PATH), but the first is the preferred method since it keeps the installation in one place, making
upgrading or uninstalling easier.
Configure IIS
For these steps, open IIS Manager
(Start -> Control Panel -> Administrative Tools -> Internet Information Services (IIS) Manager).
Then add new extension (.php)
Right-click on "Web Sites" in the left pane, then click "Properties" in the menu that pops up
Click "Configuration"
Click Add...
Enter the full path to php5isapi.dll in the "Executable" textbox (Browse... to find it more easily if you
need to)
Search for the section that has a series of commented out "LoadModule" statements. Add the
following line after all the LoadModule statements:
LoadModule php5_module "c:/php/php5apache2.dll"
Search for "AddType" and add the following line after the last "AddType" statement:
AddType application/x-httpd-php .php
If you need to support other file types, like ".php3" and ".phtml", simply add them to the list, like this:
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .phtml
Test your setup
Create a new file named test.php in one of the websites. Expand the Web Sites folder in the left pane of IIS
Manager to see a list of existing websites. Right-click on a website -> Properties -> Home Directory ->
Local Path will show you where the website root directory is.
Create test.php file with the following line: <?php phpinfo(); ?>
With your browser go to http://localhost/test.php
After loading test.php, you should see some information about your PHP installation. Be sure to scroll all the
way down to the bottom to see that there were no errors. Pay attention to "Configuration File (php.ini) Path"
field. Field's value is current location of php.ini file and you should make appropriate changes in it.
Date Settings (for PHP 5.1 or newer)
It is strongly recommended to configure date settings in php.ini. It is not safe to rely on the system's time
zone settings.
Set date.timezone in php.ini to your time zone (in my example it's Europe/Moscow).
Complete list of Timezones you can see at http://php.net/manual/en/timezones.php
Location of libmysql.dll
Lastly, we need to be sure that copy of libmysql.dll is located in PHP folder (for PHP 5.0 or newer).
<html>
<head>
<title>First PHP Script</title>
</head>
<body>
<?php echo "<b>Hello World!</b>"; ?> //outputs a message
</body>
</html>
The output of this last script will be pretty much the same as the first one, except that the new document will
also have a title: "First PHP Script", and the welcome message will be written using bold characters.
Note: If you view the source html code from the browser application, all php code is hidden. It was
all processed before the browser application could view the page.
PHP: Variables
A variable is a holder for a type of data. So, based on its type, a variable can hold numbers, strings,
booleans, objects, resources or it can be NULL. In PHP all the variables begin with a dollar sign "$" and the
value can be assignes using the "=" operator. The dollar sign is not technically part of the variable name, but
it is required as the first character for the PHP parser to recognize the variable as such.
Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP we needn't
have to specify the variable type, as it takes the data type of the assigned value. The contents of a variable
can be changed at any time, and so can its type. To declare a variable, you must include it in your script. You
can declare a variable and assign it a value in the same statement.
Here is some code creating and assigning values to a couple of variables:
<?php
//Commented lines starting with the double
//forward slash will be ignored by PHP
//First we will declare a few variables
//and assign values to them
$myText = "Have a nice day!";
$myNum = 5;
//Note that myText is a string and myNum is numeric.
//Next we will display these to the user.
echo $myText;
//To concatenate strings in PHP, use the '.' (period) operator
echo "My favourite number is ". $myNum
?>
The output is: Have a nice day! My favourite number is 5.
Case Sensitivity
One thing that causes many problems and take hours of finding mistakes is case sensitivity. PHP is case
sensitive. Have a look at the following code:
<?php
$myVar = "WebCheatSheet";
$myvar = "PHP tutorial";
echo "$myVar - $myvar"; //outputs "WebCheatSheet - PHP tutorial"
?>
PHP Variable Naming Conventions
There are a few rules that you need to follow when choosing a name for your PHP variables.
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.
One important thing to note if you are coming from another programming language there is no size limit for
variables.
Variable References
PHP also allows you to do some neat things with variables. It allows you to create aliases for variables, and
it also allows you to have variables whose name is a variable. A variable reference, or alias, is a variable
assigned to refer to the same information as another variable. To assign an alias to a variable, you use the
reference operator, which is an equals sign followed by an ampersand. The following code snippet outputs
'Have a nice day!' twice:
<?php
$firstVar = 'nice day!';
//Assign the value 'nice day!' to $firstVar
$secondVar = &$firstVar;
// Reference $firstVar via $secondVar.
$secondVar = "Have a $secondVar"; // Alter $secondVar...
echo $firstVar;
echo $secondVar;
?>
Environment Variables
Beyond the variables you declare in your code, PHP has a collection of environment variables, which are
system defined variables that are accessible from anywhere inside the PHP code. All of these environment
variables are stored by PHP as arrays. Some you can address directly by using the name of the index
position as a variable name. Other can only be accessed through their arrays.
Some of the environment variables include:
$_SERVER
Contains information about the server and the HTTP connection. Analogous to the old
$HTTP_SERVER_VARS array (which is still available, but deprecated).
$_COOKIE
Contains any cookie data sent back to the server from the client. Indexed by cookie name.
Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but
deprecated).
$_GET
Contains any information sent to the server as a search string as part of the URL.
Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).
$_POST
Contains any information sent to the server as a POST style posting from a client form.
Analogous to the old $HTTP_POST_VARS array (which is still available, but
deprecated).
$_FILE
$_ENV
Contains information about environmental variables on the server. Analogous to the old
$HTTP_ENV_VARS array (which is still available, but deprecated).
?>
As you can see, elements in an array can be any type of data (string, integer, double) and can also be other
variables. An individual array element can be of any type, including another array.If you want to find out if a
variable contains an array you can use the is_array() function. Notice that Indexed arrays start at position
zero, not at position one, so your first array element has an index of 0, and the highest position in the array is
one less than the number of elements in the array.
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them. Have a look at the following
example:
<?php
$first_array = array("key1" => "the first element", "key2" => "the second element");
$second_array = array(
"key3" => "this is the first element of the second array",
"key4" => "this is the second element of the second array",
);
echo $first_array['key1']; //prints "the first element."
echo $second_array['key3']; //prints "the first element of the second array"
echo $first_array['key2']; //prints "the second element"
echo $second_array['key4']; //prints "this is the second element of the second array"
?>
Right, now you know how to define an associative array, but you probably don't see yet how useful are they.
Well think of this, say you have a flower-shop. You have 3 different flowers, and each flower has a different
price. Let's make this example in php.
<?php
//We initialize the array using the array() function.
//Note that for readability one can spread the argument over several lines.
$flower_shop = array (
"rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00"
);
echo "rose costs $flower_shop['rose'], daisy costs $flower_shop['daisy'], and orchild costs $flower_shop['orchild'].";
?>
Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to
work with the array. We can use the foreach loop. In the following example we use the foreach loop to
iterate through our flowers_shop array, and read them into a table. Note carefully the syntax.
<?php
//We initialize the array using the array() function.
//Note that for readability one can spread the argument over several lines.
$flower_shop = array (
"rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00",
);
//let's print out the headers to our table
echo "<table border='1' cellpadding='5'>";
echo"<tr><th>Flower</th><th>Price</th></tr>";
//Now we start the foreach loop using the variable $flower to hold our key
//and $price to hold our cost.
foreach($flower_shop as $Flower=>$Price)
{
echo "<tr><td>$Flower </td><td>$Price</td></tr> "; //print the values into a table cell for each iteration
}
//finally close the table
echo "</table>";
?>
Multidimensional Arrays
In preceding example you've learned how to use arrays. But what if you want to give more information on
each flower? You now have the cost, but what if you wanted to add the number of flowers you get for that
price, and the colour of the flower? One of the ways to do it is using multidimensional arrays.
A multidimensional array is an array that contains at least one other array as the value of one of the indexes.
Example below shows how to use multidimensional array:
<?php
//Initialize the array using the array() function.
$flower_shop = array(
"rose" => array( "5.00", "7 items", "red" ),
"daisy" => array( "4.00", "3 items", "blue" ),
"orchid" => array( "2.00", "1 item", "white" ),
);
//print "rose costs 5.00, and you get 7 items."
echo "rose costs ".$flower_shop['rose'][0].", and you get ".$flower_shop['rose'][1].".";
//print "daisy costs 4.00, and you get 3 items."
echo "daisy costs ".$flower_shop['daisy'][0].", and you get ".$flower_shop['daisy'][1].".";
//print "orchild costs 2.00, and you get 1 item.
echo "orchid costs ".$flower_shop['orchid'][0].", and you get ".$flower_shop['orchild'][1].".";
?>
PHP: How to Sort an Array
It is often necessary to arrange the elements in an array in numerical order from highest to lowest values
(descending order) or vice versa (ascending order). If the array contains string values, alphabetical order
may be needed. Sorting a one-dimensional arrays is quite easy.
Sorting numerically indexed arrays
Sorting associative arrays
Sorting arrays in the reverse order
Sorting Numerically Indexed Arrays
At first we will consider an array which contains string values. The code below sorts array elements in
ascending alphabetical order:
<?php
$flowers = array("rose", "daisy" , "orchid", "tulip", "camomile");
sort($flowers);
for ($i=0; $i <= 4; $i++) //prints the array elements
echo $flowers[$i]."<br \>";
?>
Now array elements will go in the alphabetical order. Output will be the following:
camomile
daisy
orchid
rose
tulip
We can sort values by numerical order too. If we have an array containing the prices of flowers, we can sort
it into ascending numeric order. Have a look at the example:
<?php
$prices = array(1.25, 0.75 , 1.15, 1.00, 0.50);
sort($prices);
for ($i=0; $i <= 4; $i++) //prints the array elements
echo $prices[$i]."<br \>";
?>
The prices will now be in the following order:
0.50
0.75
1.00
1.15
1.25
Note that the sort function is case sensitive, i.e. all capital letters come before all lowercase letters. So "A" is
less than "Z", but "Z" is less than "a".
Back to top
Sorting Associative Arrays
If we are using an associative array we cannot sort an array by using the sort() function. If we apply the
sort() function on an associative array, it is sorted by the numeric value of the index. To sort an associative
array we need to use the asort() function to keep keys and values together as they are sorted.
The following code creates an associative array containing the three flowers and their associated prices, and
then sorts the array into ascending price order:
<?php
$shop = array ( "rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00",
);
asort($shop);
foreach($shop as $key => $value)
echo $key." costs ".$value." dollars<br />"; //print the array elements
?>
The above example will output:
orchid costs
daisy costs
rose costs 5.00 dollars
2.00
4.00
dollars
dollars
The asort() function orders the array according to the value of each element. In the array, the values are the
prices and the keys are the names of the flowers.
If instead of sorting by price we want to sort by flower name, we use ksort() function to sort an associative
array according to the key.
The following code will result in the keys of the array being ordered alphabetically:
<?php
$shop = array ( "rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00",
);
ksort($shop);
foreach($shop as $key => $value)
echo $key." costs ".$value." dollars<br />"; //print the array elements
?>
Output will be the following:
daisy costs
orchid costs
rose costs 5.00 dollars
4.00
2.00
dollars
dollars
Back to top
Sorting Arrays in the Reverse Order
We discussed sort(), asort(), and ksort() functions. All these functions sort array in the ascending order. Each
of them has corresponding function that sorts an array in the descending order. These reverse functions are
called rsort(), arsort() and krsort() respectively.
Reverse sorting functions are used the same way as usual sorting functions. Rsort() function sorts onedimensional numerically indexed array by the values in reverse order. Arsort() function sorts onedimensional associative array by the values in reverse order. Krsort() function sorts one-dimensional
associative array by the keys in reverse order.
PHP: Multidimensional Arrays
Array does not have to be a simple list of keys and values; each array element can contain another array as a
value, which in turn can hold other arrays as well. In such a way you can create two-dimensional or threedimensional array.
Two-dimensional Arrays
Three-dimensional Arrays
Two-dimensional Arrays
Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices.
But if you need to keep more than one item of each type you need to use something different - one of the
ways to do it is using multidimensional arrays. The table below might represent our two-dimensional array.
Each row represents a type of flower and each column a certain attribute.
Title
Price
Number
rose
1.25
15
daisy
0.75
25
orchid
1.15
To store data in form of array represented by preceding example using PHP, lets prepare the following code:
<?php
$shop = array( array("rose", 1.25 , 15),
array("daisy", 0.75 , 25),
array("orchid", 1.15 , 7)
);
?>
This example shows that now $shop array, in fact, contains three arrays. As you remember, to access data in
one-dimensional array you have to point to array name and index. The same is true in regards to a twodimensional array, with one exception: each element has two indexes row and column.
To display elements of this array we could have organize manual access to each element or make it by
putting For loop inside another For loop:
<?php
echo "<h1>Manual access to each element</h1>";
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";
echo "<h1>Using loops to display array elements</h1>";
echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
echo "<li><b>The row number $row</b>";
echo "<ul>";
for ($col = 0; $col < 3; $col++)
{
echo "<li>".$shop[$row][$col]."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ol>";
?>
Perhaps, instead of the column numbers you prefer to create their names. For this purpose, you can use
associative arrays. The following code will store the same set of flowers using column names:
<?php
$shop = array( array( Title => "rose",
Price => 1.25,
Number => 15
),
array( Title => "daisy",
Price => 0.75,
Number => 25,
),
array( Title => "orchid",
Price => 1.15,
Number => 7
)
);
?>
It is easier to work with this array, in case you need to get a single value out of it. Necessary data can be
easily found, if you turn to a proper cell using meaningful row and column names that bear logical content.
However, we are loosing the possibility to use simple for loop to view all columns consecutively.
You can view outer numerically indexed $shop array using the for loop. Each row of the $shop array is an
associative array. Hence, inside the for loop you need for each loop. Also you can get each element from
associative array manualy:
<?php
echo "<h1>Manual access to each element from associative array</h1>";
for ($row = 0; $row < 3; $row++)
{
echo $shop[$row]["Title"]." costs ".$shop[$row]["Price"]." and you get ".$shop[$row]["Number"];
echo "<br />";
}
echo "<h1>Using foreach loop to display elements</h1>";
echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
echo "<li><b>The row number $row</b>";
echo "<ul>";
foreach($shop[$row] as $key => $value)
{
echo "<li>".$value."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ol>";
?>
Back to top
Three-dimensional Arrays
You dont have to be limited by two dimensions: the same way as array elements can contain other arrays,
these arrays, in their turn, can contain new arrays.
Three-dimensional array is characterized by height, width, and depth. If you feel comfortable to imagine
two-dimensional array as a table, then imagine a pile of such tables. Each element can be referenced by its
layer, row, and column.
If we classify flowers in our shop into categories, then we can keep data on them using three-dimensional
array. We can see from the code below, that three-dimensional array is an array containing array of arrays:
<?php
$shop = array(array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
),
array(array("rose", 1.25, 15),
Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to
execute a statement if the condition is false. The syntax for If statement looks as follows:
if (condition) {
statements_1
} else {
statements_2
}
Condition can be any expression that evaluates to true or false. If condition evaluates to true,
statements_1 are executed; otherwise, statements_2 are executed. statement_1 and statement_2 can be any
statement, including further nested if statements.
You may also compound the statements using elseif to have multiple conditions tested in sequence. You
should use this construction if you want to select one of many sets of lines to execute.
if (condition_1) {
statement_1
}
[elseif (condition_2) {
statement_2
}]
...
[elseif (condition_n_1) {
statement_n_1
}]
[else {
statement_n
}]
Let's have a look at the examples. The first example decides whether a student has passed an exam with a
pass mark of 57:
<?php
$result = 70;
if ($result >= 57) {
echo "Pass <br />";
}
else {
echo "Fail <br />";
}
?>
Next example use the elseif variant on the if statement. This allows us to test for other conditions if the first
one wasn't true. The program will test each condition in sequence until:
It finds one that is true. In this case it executes the code for that condition.
It reaches an else statement. In which case it executes the code in the else statement.
It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement after
the conditional structure.
<?php
$result = 70;
if ($result >= 75) {
echo "Passed: Grade A <br />";
}
elseif ($result >= 60) {
echo "Passed: Grade B <br />";
}
elseif ($result >= 45) {
echo "Passed: Grade C <br />";
}
else {
echo "Failed <br />";
}
?>
Back to top
Switch Statement
Switch statements work the same as if statements. However the difference is that they can check for multiple
values. Of course you do the same with multiple if..else statements, but this is not always the best approach.
A switch statement allows a program to evaluate an expression and attempt to match the expression's value
to a case label. If a match is found, the program executes the associated statement. The syntax for the switch
statement as follows:
switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_n
[break;]
}
The program first looks for a case clause with a label matching the value of expression and then transfers
control to that clause, executing the associated statements. If no matching label is found, the program looks
for the optional default clause, and if found, transfers control to that clause, executing the associated
statements. If no default clause is found, the program continues execution at the statement following the end
of switch. Use break to prevent the code from running into the next case automatically.
Let's consider an example:
<?php
$flower = "rose";
switch ($flower)
{
case "rose" :
echo $flower." costs $2.50";
break;
case "daisy" :
echo $flower." costs $1.25";
break;
case "orchild" :
echo $flower." costs $1.50";
break;
default :
echo "There is no such flower in our shop";
break;
}
?>
However, in addition to simple equality you can also test the expression for other conditions, such as greater
than and less than relationships. The expression you are testing against must be repeated in the case
statement. Have a look at the example:
<?php
$myNumber = 5;
switch ($myNumber) {
case 0:
echo "Zero is not a valid value.";
break;
case $myNumber < 0:
echo "Negative numbers are not allowed.";
break;
default:
echo "Great! Ready to make calculations.";
break;
}
?>
If an expression successfully evaluates to the values specified in more than one case statement, only the first
one encountered will be executed. Once a match is made, PHP stops looking for more matches.
Back to top
Type conversion rules to Boolean
1. When converting to Boolean, the following values are considered FALSE:
o
o
o
o
o
o
o
boolean False
integer zero (0)
double zero (0.0)
empty string and string "0"
array with no elements
object with no elements
special value NULL
The While statement executes a block of code if and as long as a specified condition evaluates to true. If the
condition becomes false, the statements within the loop stop executing and control passes to the statement
following the loop. The While loop syntax is as follows:
while (condition)
{
code to be executed;
}
The block of code associated with the While statement is always enclosed within the { opening and } closing
brace symbols to tell PHP clearly which lines of code should be looped through.
While loops are most often used to increment a list where there is no known limit to the number of iterations
of the loop. For example:
while (there are still rows to read from a database)
{
read in a row;
move to the next row;
}
Let's have a look at the examples. The first example defines a loop that starts with i=0. The loop will
continue to run as long as the variable i is less than, or equal to 10. i will increase by 1 each time the loop
runs:
<?php
$i=0;
while ($i <= 10) { // Output values from 0 to 10
echo "The number is ".$i."<br />";
$i++;
}
?>
Now let's consider a more useful example which creates drop-down lists of days, months and years. You can
use this code for registration form, for example.
<?php
$month_array = array( "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");
echo "<select name=\"day\">";
$i = 1;
while ( $i <= 31 ) {
echo "<option value=".$i.">".$i."</option>";
$i++;
}
echo "</select>";
echo "<select name=\"month\">";
$i = 0;
while ( $i <= 11 ) {
echo "<option value=".$i.">".$month_array[$i]."</option>";
$i++;
}
echo "</select>";
}
echo "<p><b>One more example of using the Break statement:</b><p>";
$i = 0;
$j = 0;
while ($i < 10) {
while ($j < 10) {
if ($j == 5) {break 2;} // breaks out of two while loops
$j++;
}
$i++;
}
echo "The first number is ".$i."<br />";
echo "The second number is ".$j."<br />";
?>
The Continue statement terminates execution of the block of statements in a While or For loop and continues
execution of the loop with the next iteration:
<?php
echo "<p><b>Example of using the Continue statement:</b><p>";
for ($i=0; $i<=10; $i++) {
if (i==3){continue;}
echo "The number is ".$i;
echo "<br />";
}
?>
PHP: Functions
A function is a block of code which can be called from any point in a script after it has been declared. It
is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code
contained within functions is ignored until the function is called from another part in the script.
Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase
legibility by tiding up complicated code sequences.
It is good programming practice to use functions to modularize your code and to better provide reuse.
To declare a function, you simply type:
<?php
function function_name(param_1, ... , param_n)
{
statement_1;
statement_2;
...
statement_m;
return return_value;
}
?>
We can optionally pass parameters to the functions to be known as local variable, and we can also
return a result with the "return value" statement. This produces the ending of the function returning a
value.
Let's create two functions that will print the string "PHP Functions" five times, but the first one will not
contain parameters, and the second one will. A function parameter is nothing more than a piece of data
that the function requires to execute. In above example also included code to call the function.
<?php
function firstFunction()
{
for($i = 0; $i != 5; $i++)
echo "<P>PHP Functions!</P>";
}
//let's add parameters to that function
function secondFunction($num, $msg)
{
for($i = 0; $i != $num; $i++)
echo "<P>". $msg ."</P>";
}
echo "This is before the functions is called<br>";
echo "The first function output is:"
firstFuction(5,"This is a function with parameters");
echo "The second function output is:";
secondFuction(5,"This is a function with parameters");
echo "This is after the function has been called<br>";
?>
Next example creates a function that will calculate arithmetic mean and return a result with the "return
value" statement:
<?php
function aritmetic_mean($a, $b)
{
$result = ( $a + $b ) / 2;
return $result;
}
//print the the results of calculation
echo aritmetic_mean(4,6),"<br>";
echo aritmetica_mean(3242,524543),"<br>";
?>
While the scope of a variable defined in a function is local to that function, a variable defined in the
main body of code has a global scope. The "global" keyword tells PHP to look for a variable that has
been defined outside the function.
And what about lifetime for a variable? A variable defined within a PHP program script exists only while
that script is running. When the script ends, the variable ceases to exist. This seems pretty obvious!
Now apply it to a function: a variable defined within a function exists only while that function is being
processed; when the function ends, the variable ceases to exist.
The example HTML page above includes different form elements: input fields, select list, text area,
radio buttons, checkboxes and a submit button. When a user fills in this form and clicks on the submit
button, the form data is sent to the process.php file.
Notice that we have added square brackets [] to the name of the checkbox element. The reason for the
square brackets is that it informs PHP that the value may be an array of information. Users can select
multiple values, and PHP will place them all into an array of the value of the name attribute.
For example, if you pick Green and Yellow and submit the form, then $_POST['Colors'] is itself an
array. $_POST['Colors'][0] is Green and $_POST['Colors'][1] is Yellow. That's because the name
attribute of the checkbox element is Colors[]. If the name was just Colors, then $_POST['Colors']
would be a string, holding only one of the selected values.
Back to top
Next, we are going to create our PHP file that will process the data. When you submit your HTML form
PHP automatically populates two superglobal arrays, $_GET and $_POST, with all the values sent as
GET or POST data, respectively. Therefore, a form input called 'Name' that was sent via POST, would be
stored as $_POST['Name'].
Copy and paste this code and save it as process.php in the same directory as form.html.
<?php
//Check whether the form has been submitted
if (array_key_exists('check_submit', $_POST)) {
//Converts the new line characters (\n) in the text area into HTML line breaks (the <br />
tag)
$_POST['Comments'] = nl2br($_POST['Comments']);
//Check whether a $_GET['Languages'] is set
if ( isset($_POST['Colors']) ) {
$_POST['Colors'] = implode(', ', $_POST['Colors']); //Converts an array into a single
string
}
//Let's now print out the received values in the browser
echo "Your name: {$_POST['Name']}<br />";
echo "Your password: {$_POST['Password']}<br />";
echo "Your favourite season: {$_POST['Seasons']}<br /><br />";
echo "Your comments:<br />{$_POST['Comments']}<br /><br />";
echo "You are from: {$_POST['Country']}<br />";
echo "Colors you chose: {$_POST['Colors']}<br />";
} else {
echo "You can't see this page without submitting the form.";
}
?>
Let's give a little explanation. At the first line we check whether the form has been submitted and the
php script has not been called directly. Next we convert the new line characters in the text area into
HTML line breaks. Then we check whether a $_POST['Colors'] is set and if so we use implode() function
to convert $_POST['Colors'] array into a single string. Finally, we print out all received values in the
browser.
Back to top
PHP: Cookies
A cookie is a message given to a Web browser by a Web server. The browser stores the message in a
small text file that the server embeds on the user's computer. Each time the same computer requests a
page with a browser, the cookie is sent back to the server too.
There are a wide variety of things you can do with cookies. They are used to store information about
user, visited pages, poll results and etc. The main purpose of cookies is to identify users and possibly
prepare customized Web pages for them.
The cookie name. The name of each cookie sent is stored in the superglobal array
$_COOKIE.
[value] The cookie value. It is associated with the cookie name.
[expire] The time after which the cookie should expire in seconds
[path] Specifies the exact path on the domain that can use the cookies.
[domain] The domain that the cookie is available. If not domain is specified, the default value is
the value of the domain in which cookie was created.
[security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the
cookie is sent over a secure connection but it doesn't mean that the cookie is secure. It's just a
text file like every other cookie. A value of 0 denotes a standard HTTP transmission.
In the example below, we will create a cookie named "myCookie" and assign the value "PHP Tutorial" to
it. We also specify that the cookie should expire after one hour and that the cookie is available for all
pages within a Tutorials directory.
[name]
<?php
setcookie("myCookie", "PHP Tutorial", time()+3600, "/tutorials");
?>
There's one important item to mention about using cookies. Because of the way cookies work within
HTTP, it's important that you send all cookies before any output from your script. This requires that you
place calls to this function before any output, including tags as well as any whitespace. If you don't,
PHP will give you a warning and your cookies will not be sent.
This would show up on the page as: "myCookie value is PHP Tutorial".
the GD library installed. In this tutorial we will show you how to get quite interesting and useful effects
using image handling functions. We will review two practical tasks: creating security images (captcha)
on the fly and building a bar chart using numerical values retrieved from MySQL database.
To create a new image or edit an existing one, we need to create image identifier. In the preceding
example we created an empty canvas by calling ImageCreate() function, passing it width and height of
a new image as a parameters. Another way to do it is to read the existing image from the file.
Depending on the file format you can do it using one of the following functions:
ImageCreateFromPNG(), ImageCreateFromGIF(), ImageCreateFromJPEG(). Parameter of each function
is a file name.
Then, we need to choose colors to be used while painting. For this we can use ImageColorAllocate()
function and image identifiers for red, green, and blue (RGB) components of necessary color will be
passed as parameters.
On the next step, we will generate our image. First, using ImageFill() function we will create black
background. Parameters of this function are: image identifier, initial coordinates of the area to be filled
and fill color. Then, we will use ImageString() function to add text to the image. Its parameters are
image identifier, font, coordinates for the first text position and text color. Finally, we will draw two lines
and a rectangular to protect our image a little bit. Please note, that the final point of the rectangular
has the following coordinates: $width-1 and $height-1. If they were equal to $width and $height, than
the rectangular would have exceeded canvas frame.
When we had created the image, we can output it either to a browser, or to
how to output it to the browser. We need to inform the browser, that we will
text or html-code. To do it, call Header() function, setting image MIME-type.
Header() function can not be executed if HTTP header has already been
header we can output our image using ImageJpeg() function, passing
parameter.
When we have finished working with the image we need to free up resources using ImageDestroy()
function.
Back to top
Script building a bar chart is quite long, so let's divide it into two parts and discuss them separately.
The first part of the script connects to MySQL database and requests data that will be represented in
the bar chart.
<?php
//Querying the database to get poll results
//connection to the database
$dbhandle = mysql_connect("localhost", "root", "")
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poll",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM results");
$num_poller = mysql_num_rows($result);
$total_votes = 0;
//fetch the data from the database
while ($row = mysql_fetch_array($result)) {
$total_votes += $row{'num_votes'}; //calculating total number of votes
}
//nulling the pointer $result
mysql_data_seek($result,0);
In the second part of the script first of all we will calculate variables needed to build the chart. Then,
we prepare primary image and actually output data. Results for each genre are picked from the
database one by one, percentage of votes is calculated, and then bars and explanatory notes are
outputted.
In this script we are using TrueType fonts to get anti-aliased text. Functions that work with the
TrueType fonts have its own peculiarities. First, you need to point where the fonts are located. For this,
system variable GDFONTPATH is set. Then, we need to set the font name. TrueType fonts are rendered
using ImageTTFText().
We have already discussed above all functions used for drawing, the code has been commented and is
quite clear, so you shouldnt have any trouble.
//Tell gd2, where your fonts reside
putenv('GDFONTPATH=C:\WINDOWS\Fonts');
$font = 'arial';
//Set starting point for drawing
$y = 50;
//Specify constant values
$width = 700; //Image width in pixels
$bar_height = 20; //Bars height
$height = $num_poller * $bar_height * 1.5 + 70; //Calculating image height
$bar_unit = ($width - 400) / 100; //Distance on the bar chart standing for 1 unit
//Create the image resource
$image = ImageCreate($width, $height);
//We are
$white =
$black =
$red
=
$blue =
There are some rules you need to follow when constructing your HTML form. First, make sure that the
form uses the POST method. Second, the form needs the following attribute: enctype="multipart/formdata". It specifies which content-type to use when submitting information back to server. Without these
requirements, your file upload will not work.
Another thing to notice is the hidden form field named MAX_FILE_SIZE. Some web browsers actually
pick up on this field and will not allow the user to upload a file bigger than this number (in bytes). You
should set this value to coincide with the maximum upload size that is set in your php.ini file. It is set
with the upload_max_filesize directive and the default is 2MB. But it still cannot ensure that your script
won't be handed a file of a larger size. The danger is that an attacker will try to send you several large
files in one request and fill up the file system in which PHP stores the decoded files. Set the
post_max_size directive in your php.ini file to the maximum size that you want (must be greater than
upload_max_filesize). The default is 10MB. This directive controls the maximum size of all the POST
data allowed in a single request. Also make sure that file_uploads inside your php.ini file is set to On.
At least, have a look at the input tag attribute: type="file". It is used to designate the input element as
a file select control. This provides a place for the URI of a file to be typed and a "Browse" button which
can be used as an alternative to typing the URI.
After the user enters the URI of a file and clicks the Submit button the copy of the file will be sent to
the server and the user will be redirected to upload.php. This PHP file will process the form data.
Back to top
the original name of the file uploaded from the user's machine
the MIME type of the uploaded file (if the browser provided the
$_FILES["uploaded_file"]["name"]
$_FILES["uploaded_file"]["type"]
type)
$_FILES["uploaded_file"]["size"]
$_FILES["uploaded_file"]["tmp_name"]
server
$_FILES["uploaded_file"]["error"] an error code resulting from the file upload
The example below accepts an uploaded file and saves it in the upload directory. It allows to upload
only JPEG images under 350Kb. The code, itself, is rather clear, but we will give a little explanation.
Have a look at the example and save this PHP code as upload.php.
<?php
//heck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 350000)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
?>
Before you do anything with the uploaded file you need to determine whether a file was really
uploaded. After that we check if the uploaded file is JPEG image and its size is less than 350Kb. Next
we determine the path to which we want to save this file and check whether there is already a file with
such name on the server. When all checks are passed we copy the file to a permanent location using
the move_upload_file() function. This function also confirms that the file you're about to process is a
legitimate file resulting from a user upload. If the file is uploaded successfully then the
corresponding message will appear.
Note: Be sure that PHP has permission to read and write to the directory in which temporary files are
saved and the location in which you're trying to copy the file.
This example is rather simple and its propose is to demonstrate you how to upload files using PHP. For
example, you can add new conditions and allow to upload GIF and PNG images, or any other kind of
files that you want. If you are unfamiliar with PHP this tutorial may be a good place to start.
Note that to send email with PHP you need a working email server that you have permission to use: for
Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in
your php.ini file to point to your email server.
As you can see, it very easy to send an email. You can add more receivers by either adding their
addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don't receive
the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.
Back to top
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we
have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies
two versions of the email. To include an attachment to our message, we read the data from the
specified file into a string, encode it with base64, split it in smaller chunks to make sure that it
matches the MIME specifications and then include it as an attachment.