Вы находитесь на странице: 1из 37

What is PHP?

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 ?>.

What can you do with PHP?


There are many things you can do with PHP. You can display date, time, and other information in different
ways. You can make a survey form and ask people who visit your site to fill it out. 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. You can also send e-mail, work with newsgroups,etc.
PHP offers plenty of possibilities:

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.

2. Download and unzip the latest version of PHP


3. Rename/copy php.ini-recommended to php.ini
4. Create a session state directory and point the session.save_path variable in php.ini to it
5. Setup the PHP extensions
6. Make sure that PHP folder is in the system path
7. Configure IIS
8. Configure Apache Web Server
9. Test your setup
10. Date Setting
11. Location of libmysql.dll
Download and unzip the latest version of PHP
Download the latest zipped distribution of PHP from http://php.net. Unzip it. The recommendation is to put
all the PHP stuff in a folder just off of the root drive (avoid whitespace), like C:\PHP.
Rename/copy php.ini-recommended to php.ini
In your PHP directory, you'll find a couple of php.ini-* files. They are pre-configured settings for a PHP
install that you can use as an initial setup. The php.ini-recommended is the most secure, hence, the
recommended one; just rename it to php.ini and copy to your Windows directory.
Create a session state directory and point the session.save_path variable in php.ini to it
This is optional, but recommended step. PHP does not need sessions, but it's something that will most likely
be useful.
Create a session directory somewhere on the server. I created C:\PHP\sessionFolder. This directory will hold
many small files with session variable information for PHP.
Now change the value of the session.save_path variable in php.ini to be the full path to that directory
(session.save_path=C:\PHP\sessionFolder).

Setup the PHP extensions


You need to point PHP to the directory that holds the extension libraries and you need to uncomment the
desired extensions.

Point PHP to the correct directory:


Set extension_dir in php.ini to "C:\PHP\ext" (extension_dir = "C:\PHP\ext")

Uncomment the ones you want to use.


Its important to be sure that php_mysql.dll extension is uncommented (for PHP 5 or newer).

Make sure that PHP folder is in the system path


You should add "C:\PHP" to the server's PATH environment variable:

Right-click on My Computer, choose Properties

Flip to the Advanced tab

Click the Environment Variables button

Double-click the Path variable in the list of System variables.

Either add "C:\PHP;" to the beginning or ";C:\PHP" to the end (sans quotes, not both).

Restart IIS for it to take effect.

(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)

Expand the local computer in the left pane

Right-click on "Web Sites" in the left pane, then click "Properties" in the menu that pops up

Flip top the Home Directory tab

Click "Configuration"

Flip to the Mappings tab

Click Add...

Enter the full path to php5isapi.dll in the "Executable" textbox (Browse... to find it more easily if you
need to)

Enter ".php" in the Extension textbox

Select radial button Limit to, enter "GET,POST,HEAD"

Click OK all the way out

This will apply to every website.


This sets up IIS to actually respond to requests for php files. Until now, IIS hadn't known what to do with
php files, you just told it to pass them through php5isapi.dll.
Configure Apache Web Server
If you want PHP to work with your Apache server, you will need to modify your Apache configuration file
to load it. There are two ways to configure Apache to use PHP: one is to configure it to load the PHP
interpreter as an Apache module. The other is to configure it to run the PHP interpreter as a CGI binary.
Unless you have a particular reason for running PHP as a CGI binary, you will probably want to load PHP as
a module in Apache, since it runs more efficiently that way.
To configure Apache to load PHP as a module to parse your PHP scripts you should make some changes in
the Apache configuration file, "httpd.conf", typically found in "c:\Program Files\Apache
Group\Apache\conf\". It also can be accessed from your program files menu.

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).

Your First PHP Script


Now that you have installed all the support software for running PHP, you are ready to learn how to do a
PHP script. Writing a PHP script is very simple. No special software is needed, except a text editor like
Notepad in which the script is written.
We should begin with some general PHP syntax rules. First, all single-line statements must conclude with a
semicolon. If PHP doesn't find a semicolon at the end of your statement, then it will continue parsing the file
until it finds one, ignoring any white-spaces or empty lines. In addition, statements that exceed a single line
(such as most conditionals) must be surrounded by { and } characters. Finally, the double forward slash (//)
represents a comment and everything past those characters until the end of the line will be ignored by PHP.
A PHP file normally contains HTML tags and some PHP scripting code. A PHP scripting block always starts
with
<?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.There is a PHP
script in the example given below. This script will display the words "Hello World!" in the web browser.
There are two basic statements to output text on the browser with PHP: echo and print. In the example given
below, the echo statement is used to display text.
<?php
echo "Hello World!"; //outputs a message
?>
Always remember to save PHP's files with the extension ".php" - this is very important, because it tells the
server how to treat these files, and run the appropriate interpreter to "understand" their contents. So just go
ahead and give it an easy-to-remember name like "first.php". If you run the web-server on your own
computer, copy the file to the root location of your web-server (usually c:\inetpub\wwwroot\). If you're not
running the server on your computer, then you must upload the file to your server. After you've put your
script where it should belong, you must open it via your web-browse. So point your web-browser to the path
of the script according to your server's address - for example, if you're running a server on your own
computer, then just load into your web-browser the file http://localhost/first.php
If everything goes ok, then you will see "Hello World!" in your web-browser's output window. If PHP is not
installed or the server didn't recognize the file's extension, you will see the source code of the script.
While the first script is pure PHP, you can incorporate it into a HTML document. Copy the code below, save
it as "second.php" and load it into your web browser.

<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 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.

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

Contains information about any uploaded files. Analogous to the old


$HTTP_POST_FILES array (which is still available, but deprecated).

$_ENV

Contains information about environmental variables on the server. Analogous to the old
$HTTP_ENV_VARS array (which is still available, but deprecated).

The code to use the environment variables will be as follows:


<?php
// moderate shortcut
$newVar = $_COOKIE["myFirstCookie"];
// full version
$newVar = $HTTP_COOKIE_VARS["myFirstCookie"];
?>
PHP: Constants
Constants just as variables are used to store information. The main difference between constants and
variables is that constant value can not be changed in the process of running program. It can be mathematic
constants, passwords, paths to files, etc. By using a constant you "lock in" the value which prevents you
from accidentally changing it. If you want to run a program several times using a different value each time,
you do not need to search throughout the entire program and change the value at each instance. You only
need to change it at the beginning of the program where you set the initial value for the constant.
Have a look at the example where we use the define function to set the initial value of a constant:
<?php
// first we define a constant PASSWORD
define("PASSWORD","admin");
echo (PASSWORD);
// will display value of PASSWORD constant, i.e. admin
echo constant("PASSWORD"); // will also display admin
echo "PASSWORD";
// will display PASSWORD
?>
PHP also provides a number of built-in constants for you. "__FILE__", for example, returns the name of the
file currently being read by the interpreter. "__LINE__" returns the line number of the file. These constants
are useful for generating error messages. You can also find out which version of PHP is interpreting the
script using the "PHP_VERSION" constant.
PHP: Arrays
Arrays can be used in many ways to store and organize data quickly and efficiently. It is one of the more
useful data types available to any programming language.
Arrays can most easily be described as an ordered list of elements. You can access the individual elements
by referring to their index position within the array. The position is either specified numerically or by name.
An array with a numeric index is commonly called an indexed array while one that has named positions is
called an associative array. In PHP, all arrays are associative, but you can still use a numeric index to access
them.
An Example of an indexed Array:
<?php
$seven = 7;
$arrayname = array( "this is an element", 5, $seven );
echo $arrayname[0]; //prints: this is an element
echo $arrayname[1]; //prints: 5
echo $arrayname[2]; //prints: 7

?>
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),

array("daisy", 0.75, 25),


array("orchid", 1.15, 7)
),
array(array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7)
)
);
?>
As this array has only numeric indexes, we can use nested for loops to display it:
<?php
echo "<ul>";
for ( $layer = 0; $layer < 3; $layer++ )
{
echo "<li>The layer number $layer";
echo "<ul>";
for ( $row = 0; $row < 3; $row++ )
{
echo "<li>The row number $row";
echo "<ul>";
for ( $col = 0; $col < 3; $col++ )
{
echo "<li>".$shop[$layer][$row][$col]."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
?>
This way of creating multidimensional arrays allows to create four- and five-dimensional arrays. Syntax
rules do not limit the number of dimensions, but the majority of practical tasks logically correspond to the
constructions of three or less dimensions.

PHP: Conditional Statements


Sometimes when you write code, you want to perform different actions for different decisions. You can use
conditional statements in your code to do this. Conditional statements are the set of commands used to
perform different actions based on different conditions. In this tutorial we will look at two structures: if...else
and switch statements. Both perform in saw way the same task.
IF ... Else Statement
Switch Statement
Type conversion rules to Boolean
If ... Else Statement
The If Statement is a way to make decisions based upon the result of a condition. For example, you might
have a script that checks if boolean value is true or false, if variable contains number or string value, if an
object is empty or populated, etc. The condition can be anything you choose, and you can combine
conditions together to make for actions that are more complicated.

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

Every other value is considered TRUE.

PHP: Looping Statements


In programming it is often necessary to repeat the same block of code a given number of times, or until a
certain condition is met. This can be accomplished using looping statements. PHP has two major groups
of looping statements: for and while. The For statements are best used when you want to perform a loop a
specific number of times. The While statements are best used to perform a loop an undetermined number of
times. In addition, you can use the Break and Continue statements within looping statements.
The While Loop
The Do...While Loop
The For Loop
The Foreach Loop
Break and Continue Statements
The While Loop

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 "<select name=\"year\">";


$i = 1900;
while ( $i <= 2007 ) {
echo "<option value=".$i.">".$i."</option>";
$i++;
}
echo "</select>";
?>
Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.
Back to top
The Do...While Loop
The Do...While statements are similar to While statements, except that the condition is tested at the end of
each iteration, rather than at the beginning. This means that the Do...While loop is guaranteed to run at least
once. The Do...While loop syntax is as follows:
do
{
code to be exected;
}
while (condition);
The example below will increment the value of i at least once, and it will continue incrementing the variable
i as long as it has a value of less than or equal to 10:
<?php
$i = 0;
do {
echo "The number is ".$i."<br/>";
$i++;
}
while ($i <= 10);
?>
Back to top
The For Loop
The For statement loop is used when you know how many times you want to execute a statement or a list of
statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more
complex, though for loops are often more convenient than While loops. The For loop syntax is as follows:
for (initialization; condition; increment)
{
code to be executed;
}
The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For
loop executes, the following occurs:
1. The initializing expression is executed. This expression usually initializes one or more loop counters,
but the syntax allows an expression of any degree of complexity.
2. The condition expression is evaluated. If the value of condition is true, the loop statements execute.
If the value of condition is false, the For loop terminates.
3. The update expression increment executes.

4. The statements execute, and control returns to step 2.


Have a look at the very simple example that prints out numbers from 0 to 10:
<?php
for ($i=0; $i <= 10; $i++)
{
echo "The number is ".$i."<br />";
}
?>
Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of
dividends, and inner loop will be responsible for generating lists of dividers for each individual number:
<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";
for ($i = 1; $i <= 9; $i++ ) { //this is the outer loop
echo "<tr>";
echo "<td>".$i."</td>";
for ( $j = 2; $j <= 9; $j++ ) { // inner loop
echo "<td>".$i * $j."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
At last let's consider the example that uses 2 variables. One to add all the numbers from 1 to 10. The other to
add only the even numbers.
<?php
$total = 0;
$even = 0;
for ( $x = 1, $y = 1; $x <= 10; $x++, $y++ ) {
if ( ( $y % 2 ) == 0 ) {
$even = $even + $y;
}
$total = $total + $x;
}
echo "The total sum: ".$total."<br />";
echo "The sum of even values: ".$even;
?>
Back to top
The Foreach Loop
The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. There are
two different versions of the Foreach loop. The Foreach loop syntaxes are as follows:

foreach (array as value)


{
code to be executed;
}
foreach (array as key => value)
{
code to be executed;
}
The example below demonstrates the Foreach loop that will print the values of the given array:
<?php
$email = array('john.smith@example.com', 'alex@example.com');
foreach ($email as $value) {
echo "Processing ".$value."<br />";
}
?>
PHP executes the body of the loop once for each element of $email in turn, with $value set to the current
element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches
the last element or upper bound of the given array.
An alternative form of Foreach loop gives you access to the current key:
<?php
$person = array('name' => 'Andrew', 'age' => 21, 'address' => '77, Lincoln st.');
foreach ($person as $key => $value) {
echo $key." is ".$value."<br />";
}
?>
In this case, the key for each element is placed in $key and the corresponding value is placed in $value.
The Foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the
value of the variable $value can be manipulated but the original value of the array remains the same.
Back to top
Break and Continue Statements
Sometimes you may want to let the loops start without any condition, and allow the statements inside the
brackets to decide when to exit the loop. There are two special statements that can be used inside loops:
Break and Continue.
The Break statement terminates the current While or For loop and continues executing the code that follows
after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many
levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of
the outermost loop.
Examples below show how to use the Break statement:
<?php
echo "<p><b>Example of using the Break statement:</b></p>";
for ($i=0; $i<=10; $i++) {
if ($i==3){break;}
echo "The number is ".$i;
echo "<br />";

}
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.

Creating a simple function

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>";
?>

Variable Scope and Lifetime


It's important to note that if you define a variable within a function, that variable is only available
within that function; it cannot be referenced in another function or in the main body of your program
code. This is known as a variable's scope. The scope of a variable defined within a function is local to
that function.
If a function needs to use a variable that is defined in the main body of the program, it must reference
it using the "global" keyword, like this:
<?php
function AddingNumbers ( )
{
global $sum = 2 + 2
}
$sum = 0
Addnumbers ( )
echo "2 + 2 = ".$sum
?>

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.

Form Processing with PHP


One of the best features of PHP is possibility to respond to user queries or data submitted from HTML
forms. You can process information gathered by an HTML form and use PHP code to make decisions
based off this information to create dynamic web pages. In this tutorial we will show how to create an
HTML form and process the data.

The HTML Form


Before you can process the information, you need to create an HTML form that will send information to
your PHP script. There are two methods for sending data: POST and GET. These two types of sending
information are defined in your HTML form element's method attribute. Also, you must specify the
location of the PHP file that will process the information.
Below is an HTML form that will send the data using the POST method. Information sent from a form
with the POST method is invisible to others and has no limits on the amount of information to send.
Copy and paste this code and save it as form.html.
<html>
<head>
<title>Process the HTML form data with the POST method</title>
</head>
<body>
<form name="myform" action="process.php" method="POST">
<input type="hidden" name="check_submit" value="1" />
Name: <input type="text" name="Name" /><br />
Password: <input type="password" name="Password" maxlength="10" /><br />
Select something from the list: <select name="Seasons">
<option value="Spring" selected="selected">Spring</option>
<option value="Summer">Summer</option>
<option value="Autumn">Autumn</option>
<option value="Winter">Winter</option>
</select><br /><br />
Choose one:
<input type="radio" name="Country" value="USA" /> USA
<input type="radio" name="Country" value="Canada" /> Canada
<input type="radio" name="Country" value="Other" /> Other
<br />
Choose the colors:
<input type="checkbox" name="Colors[]" value="green" checked="checked" /> Green
<input type="checkbox" name="Colors[]" value="yellow" /> Yellow
<input type="checkbox" name="Colors[]" value="red" /> Red
<input type="checkbox" name="Colors[]" value="gray" /> Gray
<br /><br />
Comments:<br />
<textarea name="Comments" rows="10" cols="60">Enter your comments here</textarea><br />
<input type="submit" />
</form>
</body>
</head>
</html>

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

Processing the Form Data ( PHP Code )

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

GET and POST


When defining the method to send information to the PHP script, you either use GET or POST. Both
send variables across to a script, but they do so in different ways.
The GET method sends its variables in the web browsers URL, which makes it easy to see and possibly
change the information that was sent. So this method should not be used when sending passwords or
other sensitive information. It also should not be used for any actions that cause a change in the
server, such as placing an order or updating a database. However, because the variables are displayed
in the URL, it is possible to bookmark the page.
The GET method has a limit on the amount of information than can be sent. As a result, if you send
long variables using GET, you are likely to lose large amounts of them.
The POST method sends its variables behind the scenes and has no limits on the amount of information
to be sent. Because the variables are not displayed in the URL, it is not possible to bookmark the page.

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.

How to Create a Cookie?


How to Retrieve a Cookie Data?

How to Delete a Cookie?


Normally cookies are used only to store small amounts of data. Websites can read the values from the
cookies and use the information as desired. In addition to the information it stores, each cookie has a
set of attributes that helps ensure the browser sends the correct cookie when a request to a server is
made.
Even though cookies are not harmful some people do not permit cookies due to concerns about their
privacy. In this case you have to use Sessions.

How to Create a Cookie?


PHP cookies can be set using the setcookie() function. The syntax is as follows:
setcookie(name[, value[, expire[, path[, domain[, security]]]]])

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.

How to Retrieve a Cookie Date?


Now the cookie is set and we need to retrieve the information. As mentioned above the name of each
cookie sent by your server accessed with the superglobal array $_COOKIE. In the example below we
retrieve the value of the cookie and print out its value on the screen.
<?php
echo "The cookie value is ".$_COOKIE['myCookie'];
?>

This would show up on the page as: "myCookie value is PHP Tutorial".

How to Delete a Cookie?


By default, the cookies are set to be deleted when the browser is closed. We can override that default
by setting a time for the cookie's expiration but there may be occasions when you need to delete a
cookie before the user closes his browser, and before its expiration time arrives. To do so, you should
assure that the expiration date is in the past. The example below demonstrates how to do it (setting
expiration time 1 minute ago):
<?php
setcookie("myCookie", "", time()-60);
?>

PHP: Dynamic Image Generation


Creating images on the fly can be a very useful skill. PHP has some built-in image generation functions,
further more, to generate new images or edit existing images on the fly using PHP, we need to have

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.

Creating security images on the fly


Building a bar chart
Using dynamically generated images on the other pages

Creating security images on the fly


At first, have a look at the following script that creates captcha image. Next, we will consider each step
of image generation in details.
<?php
//Send a generated image to the browser
create_image();
exit();
function create_image()
{
//Let's generate a totally random string using md5
$md5 = md5(rand(0,999));
//We don't need a 32 character long string so we trim it down to 5
$pass = substr($md5, 10, 5);
//Set the image width and height
$width = 100;
$height = 20;
//Create the image resource
$image = ImageCreate($width, $height);
//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);
//Make the background black
ImageFill($image, 0, 0, $black);
//Add randomly generated string in white to the image
ImageString($image, 3, 30, 3, $pass, $white);
//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image,0,0,$width-1,$height-1,$grey);
imageline($image, 0, $height/2, $width, $height/2, $grey);
imageline($image, $width/2, 0, $width/2, $height, $grey);
//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");
//Output the newly created image in jpeg format
ImageJpeg($image);
//Free up resources
ImageDestroy($image);
}
?>

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.

a file. Our example shows


output the image, not the
Its worth mentioning that
sent. After sending the
it image identifier as a

When we have finished working with the image we need to free up resources using ImageDestroy()
function.
Back to top

Building a bar chart


In the example below, using graphic functions we will build a bar chart based on the values stored in
MySQL database. In our case, values represent poll results.
In this example we will use poll database. To create it run the following SQL script in your MySQL
server:
CREATE DATABASE `poll`;
USE poll;
CREATE TABLE `results` (
book_type VARCHAR(50),
num_votes INT
);
INSERT INTO `results` values
('Classic', 15),
('Fantasy', 7),
('Humor', 32),
('Mystery', 12),
('Poetry', 25);

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);

//close the connection


mysql_close($dbhandle);

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 =

making four colors, white, black, blue and red


ImageColorAllocate($image, 255, 255, 255);
ImageColorAllocate($image, 0, 0, 0);
ImageColorAllocate($image, 255, 0, 0);
imagecolorallocate($image,0,0,255);

//Create image background


ImageFill($image,$width,$height,$white);
//Draw background shape
ImageRectangle($image, 0, 0, $width-1, $height-1, $black);
//Output header
ImageTTFText($image, 16, 0, $width/3 + 50, $y - 20, $black, $font, 'Poll Results');
while ($row = mysql_fetch_object($result)) {
if ($total_votes > 0)
$percent = intval(round(($row->num_votes/$total_votes)*100));
else
$percent = 0;
//Output header for a particular value
ImageTTFText($image,12,0,10, $y+($bar_height/2), $black, $font, $row->book_type);
//Output percentage for a particular value
ImageTTFText($image, 12, 0, 170, $y + ($bar_height/2),$red,$font,$percent.'%');
$bar_length = $percent * $bar_unit;
//Draw a shape that corresponds to 100%
ImageRectangle($image, $bar_length+221, $y-2, (220+(100*$bar_unit)), $y+$bar_height, $black);
//Output a bar for a particular value
ImageFilledRectangle($image,220,$y-2,220+$bar_length, $y+$bar_height, $blue);
//Output the number of votes
ImageTTFText($image, 12, 0, 250+100*$bar_unit, $y+($bar_height/2), $black, $font, $row>num_votes.' votes cast.');
//Going down to the next bar
$y = $y + ($bar_height * 1.5);
}
//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

//Output the newly created image in jpeg format


ImageJpeg($image);
//Free up resources
ImageDestroy($image);
?>

Secure File Upload with PHP


PHP makes uploading files easy. You can upload any type of file to your Web server. But with ease
comes danger and you should be careful when allowing file uploads.
In spite of security issues that should be addressed before enabling file uploads, the actual
mechanisms to allow this are straight forward. In this tutorial we will consider how to upload files to
some directory on your Web server. We will also discuss security issues concerned with the file
uploading.

The HTML Form


Before you can use PHP to manage your uploads, you need first construct an HTML form as an
interface for a user to upload his file. Have a look at the example below and save this HTML code
as index.php.
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
Choose a file to upload: <input name="uploaded_file" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>

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

Processing the Form Data (PHP Code)


When the file was uploaded, PHP created a temporary copy of the file, and built the superglobal
$_FILES array containing information about the file. For each file, there are five pieces of data. We had
named our upload field 'uploaded_file', so the following data would exist:

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"]

the size of the uploaded file in bytes


the location in which the file is temporarily stored on the

$_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.

PHP: Sending Email (Text/HTML/Attachments)


Email is the most popular Internet service today. A plenty of emails are sent and delivered each day.
The goal of this tutorial is to demonstrate how to generate and send emails in PHP.
So, you want to send automated email messages from your PHP application. This can be in direct
response to a user's action, such as signing up for your site, or a recurring event at a set time, such as
a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions,
and so on. To understand how to send each variation that may exist on an email, we will start with the
simple example and move to the more complicated.

Sending a Simple Text Email


Sending HTML Email
Sending Email with Attachments

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.

Sending a Simple Text Email


At first let's consider how to send a simple text email messages. PHP includes the mail() function for
sending email, which takes three basic and two optional parameters. These parameters are, in order,
the email address to send to, the subject of the email, the message to be sent, additional headers you
want to include and finally an additional parameter to the Sendmail program. The mail() function
returns True if the message is sent successfully and False otherwise. Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//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";
?>

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

Sending HTML Email


The next step is to examine how to send HTML email. However, some mail clients cannot understand
HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one
part contains a plain-text version of the email and the other part is HTML. If your customers have
HTML email turned off, they will still get a nice email, even if they don't get all of the HTML markup.
Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--

<?
//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";
?>

In the preceding example we add one additional header of Content-type:multipart/alternative and


boundary string that marks the different areas of the email. Note that the content type of the message
itself is sent as a mail header, while the content types of the individual parts of the message are
embedded in the message itself. This way, mail clients can decide which part of the message they want
to display.

Sending Email with Attachment


The last variation that we will consider is email with attachments. To send an email with attachment we
need to use the multipart/mixed MIME type that specifies that mixed types will be included in the
email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML
version of the email. Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>---PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>-<?php
//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";
?>

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.

PHP: Working with Directories

Вам также может понравиться