-
Build Bright University Faculty of Information and
Technology
page: 1
Chapter 1: Introduction to PHP
Chapter 2: Data type and Variable
Chapter 3: Control Structure
Chapter 4: Loop Structure
Chapter 5: PHP Array Objects
Chapter 6: PHP Function
Chapter 7: PHP Forms
Chapter 8: PHP Date Function
Chapter 9: MySQL Database
Chapter10: PHP MySQL Database Connection
Chapter11: PHP cookies and sessions
Chapter12: PHP Include and Require
PHP and MySQL Web Application Development
-
Build Bright University Faculty of Information and
Technology
page: 2
Contents
PHP
Chapter 1: Introduction to PHP
Chapter 2: Data type and Variable
Chapter 3: Control Structure
Chapter 4: Loop Structure
Chapter 5: PHP Array Objects
Chapter 6: PHP Function
Chapter 7: PHP Forms
Chapter 8: PHP Date Function
MySQL Chapter 9: MySQL Database
Chapter10: PHP MySQL Database Connection
Chapter11: PHP cookies and sessions
Chapter12: PHP Include and Require
-
Build Bright University Faculty of Information and
Technology
page: 3
Table of Contents
PHP
Chapter 1: Introduction to PHP
Introduction to PHP
.................................................................................6
How the Pieces of the AMP Module Work Together
..............................6 Apache
.....................................................................................................7
PHP (Hypertext Preprocessor)
.................................................................7
MySQL
....................................................................................................8
Chapter 2: Data type and Variable
Overview of PHP Structure and
Syntax...................................................9 How PHP
Fits with HTML
......................................................................9
What is a PHP File?
.................................................................................9
How to write php code
.............................................................................9
PHP Comments
........................................................................................10
PHP Constants and Variables
..................................................................10
Overview of
constants........................................................................10
Overview of variables
........................................................................11
The Concatenation Operator
....................................................................12
The PHP Operators
..................................................................................13
Arithmetic Operators
.........................................................................13
Assignment Operators
........................................................................13
Comparison Operators
.......................................................................14
Logical
Operators...............................................................................14
Conditional Operator
.........................................................................14
Chapter 3: Control Structure
If Statement
..............................................................................................15
if.....else Statements
........................................................................15
if.....else if Statements
.....................................................................16
switch
Statements.....................................................................................17
Chapter 4: Loop Structure
Looping
................................................................................................19
The while Statement
................................................................................19
The do while statement
....................................................................22
The for statement
.....................................................................................23
The foreach statement
..............................................................................25
-
Build Bright University Faculty of Information and
Technology
page: 4
Chapter 5: PHP Array Objects
Introduction
..............................................................................................27
The while Statement
................................................................................27
Whats array?
...........................................................................................27
Numeric Array
.........................................................................................27
Accessing Array
Contents........................................................................30
Associative Arrays
...................................................................................30
Using Loops to Access the Array Contents
.............................................32 The foreach loop
................................................................................32
each( ) construct
.................................................................................33
list( ) construct
...................................................................................34
Multidimensional Arrays
.........................................................................36
List of Array Functions
............................................................................37
Chapter 6: PHP Function
PHP Function
...........................................................................................41
What is function?
.....................................................................................41
Naming Your Function
............................................................................42
Using Parameters
.....................................................................................43
Returning from Functions
........................................................................46
Returning Values from Functions
............................................................48
Chapter 7: PHP Forms
Overview
................................................................................................50
The GET
method......................................................................................50
The POST
method....................................................................................53
The $_REQUEST variable
......................................................................55
Using Array as form elements values
......................................................57
Chapter 8: PHP Date Function
The PHP Date( )
Function........................................................................59
Date( ) - Format the Date
.........................................................................60
MySQL
Chapter 9: MySQL Database
What is MySQL?
.....................................................................................62
Text Types
...............................................................................................62
Number Types
..........................................................................................63
Date Types
...............................................................................................63
Column Modifiers
....................................................................................63
Working with SQL Command
.................................................................64
Working with SQL statements
.................................................................65
-
Build Bright University Faculty of Information and
Technology
page: 5
Chapter 10: PHP MySQL Database Connection
How to connect to php with mysql database server?
...............................67 How to close connection
....................................................................67
How to select database
.......................................................................68
How to manipulate data from php with mysql
...................................68
Chapter 11: PHP cookies and sessions
PHP Cookies
............................................................................................71
What is a Cookie?
..............................................................................71
How to Create a Cookie?
...................................................................71
How to Retrieve a Cookie Value?
.....................................................72 How to
Delete a Cookie?
...................................................................73
PHP Sessions
...........................................................................................73
PHP Session Variables
.......................................................................73
Starting a PHP
Session.......................................................................73
Storing a Session Variable
.................................................................74
Destroying a Session
..........................................................................75
Chapter 12: PHP Include and Require
Server Side Includes (SSI)
.......................................................................76
PHP include()
Function............................................................................76
PHP require() Function
............................................................................77
Error Example require() Function
............................................................78
Error
message...........................................................................................78
-
Build Bright University Faculty of Information and
Technology
page: 6
Chapter 1:
Introduction to PHP
PHP is a powerful language and the interpreter, whether included
in a web server as a module or executed as a separate CGI binary,
is able to access files, execute commands and open network
connections on the server. These properties make anything run on a
web server insecure by default. PHP is designed specifically to be
a more secure language for writing CGI programs than Perl or C, and
with correct selection of compile-time and runtime configuration
options, and proper coding practices, it can give you exactly the
combination of freedom and security you need.
As there are many different ways of utilizing PHP, there are
many configuration options controlling its behavior. A large
selection of options guarantees you can use PHP for a lot of
purposes, but it also means there are combinations of these options
and server configurations that result in an insecure setup.
The configuration flexibility of PHP is equally rivaled by the
code flexibility. PHP can be used to build complete server
applications, with all the power of a shell user, or it can be used
for simple server-side includes with little risk in a tightly
controlled environment. How you build that environment, and how
secure it is, is largely up to the PHP developer.
How the Pieces of the AMP Module Work Together
Now that we have covered some of the history of open source, its
important to understand the role each of these programs (Apache,
MySQL, and PHP) plays in creating your Web site.
Imagine that your dynamic Web site is a fancy restaurant. Diners
come to your place, and each one wants something different and
specific. They dont worry so much about how the food is prepared,
as long as it looks and tastes delicious. Unlike a buffet-type
spread, where everything is laid out and your patrons simply choose
from whats available (the analogy being a more static,
informational Web site with little interaction and input from your
visitors), a nice restaurant encourages patron/waiter interaction
and complete customization for any specific dietary needs (a
dynamic Web site where the visitor can choose what he or she wants
to see).
In this scenario, we can attribute the three components of the
AMP module as follows:
Apache: This is your highly trained master of culinary arts, the
chef. Whatever people ask for, she prepares it without complaint.
She is quick, flexible, and able to prepare a multitude of
different types of foods. Apache acts in much the same way as your
HTTP server, parsing files and passing on the results.
PHP: This is the waiter. He gets requests from the patron and
carries them back to the kitchen with specific instructions about
how the meal should be prepared.
MySQL: This is your stockroom of ingredients (or in this case,
information).
Introduction to PHP
-
Build Bright University Faculty of Information and
Technology
page: 7
When a patron (or Web site visitor) comes to your restaurant, he
or she sits down and orders a meal with specific requirements, such
as a steak, well done. The waiter (PHP) takes those specific
requirements back to the kitchen and passes them off to the chef
(Apache). The chef then goes to the stockroom (MySQL) to retrieve
the ingredients (or data) to prepare the meal and presents the
final dish to the patron, exactly the way he or she ordered the
meal.
Apache
Apache acts as your Web server. Its main job is to parse any
file requested by a browser and display the correct results
according to the code within that file. Apache is quite powerful
and can accomplish virtually any task that you, as a Webmaster,
require.
The version of Apache covered in this book is the most recent
and stable at the time of this writing: version 2.0.47. The
features and server capabilities available in this version include
the following:
Password-protected pages for a multitude of users Customized
error pages Display of code in numerous levels of HTML, and the
capability to determine at what
level the browser can accept the content Usage and error logs in
multiple and customizable formats Virtual hosting for different IP
addresses mapped to the same server Directory Index directives to
multiple files URL aliasing or rewriting with no fixed limit
According to the Netcraft Web site (www.netcraft.com), at the
time of this writing Apache is running over 27 million Internet
servers, more than Microsoft, Sun ONE, and Zeus combined. Its
flexibility, power, and, of course, price make it a popular choice.
It can be used to host a Web site to the general public, or a
company-wide intranet, or for simply testing your pages before they
are uploaded to a secure server on another machine. Later in this
chapter, we discuss how to configure your Apache setup to
accommodate all of these options.
PHP (Hypertext Preprocessor)
PHP is a server-side scripting language that allows your Web
site to be truly dynamic. PHP stands for PHP: Hypertext
Preprocessor (and, yes, were aware PHP is a recursive cronym
probably meant to confuse the masses). Its flexibility and
relatively small learning curve (especially for programmers who
have a background in C, Java, or Perl) make it one of the most
popular scripting languages around. PHPs popularity continues to
increase as businesses and individuals everywhere embrace it as an
alternative to Microsofts ASP language and realize that PHPs
benefits most certainly outweigh the costs (three cheers for open
source!).
According to Zend Technologies, Ltd., the central source of PHP
improvements and designers of the Zend Engine, which supports PHP
applications, PHP code can now be found in approximately 9 million
Web sites.
-
Build Bright University Faculty of Information and
Technology
page: 8
The version of PHP referenced in this book is the most recent
stable release at the time of publication: version 4.3.3. Although
we discuss several of the most common uses and functions of PHP,
you can find a complete list of PHP functions in Appendix B of this
book. As you continue to program in PHP and your comfort level
increases (or the demands of your boss grow), we encourage you to
expand your use of built-in PHP functions to take advantage of its
tremendous power. You can download the PHP software from PHPs Web
site at www.php.net.
MySQL
Another open source favorite, MySQL is the database construct
that enables PHP and Apache to work together to access and display
data in a readable format to a browser. It is a Structured Query
Language server designed for heavy loads and processing of complex
queries. As a relational database system, MySQL allows many
different tables to be joined together for maximum efficiency and
speed.
This book references version 4.0.15a, the most stable release of
MySQL at the time of publication. While a complete list of features
can be found at the MySQLWeb site (www.mysql.com), some of the more
popular features of this program are as follows:
Multiple CPUs usable through kernel threads. Multi-platform
operation. Numerous column types cover virtually every type of
data. Group functions for mathematical calculations and sorting.
Commands that allow information about the databases to be easily
and succinctly
shown to the administrator. Function names that do not affect
table or column names. A password and user verification system for
added security. Up to 32 indexes per table permitted; this feature
has been successfully implemented at
levels of 60,000 tables and 5,000,000,000 rows. International
error reporting usable in many different countries.
MySQL is the perfect choice for providing data via the Internet
because of its ability to handle heavy loads and its advanced
security measures.
-
Build Bright University Faculty of Information and
Technology
page: 9
Chapter 2:
Overview of PHP Structure and Syntax
PHP programs are written using a text editor, such as Notepad or
WordPad, just like HTML pages. However, PHP pages, for the most
part, end in a .php extension. This extension signifies to the
server that it needs to parse the PHP code before sending the
resulting HTML code to the viewers Web browser.
How PHP Fits with HTML
We assume that you know some HTML before you embark on your
PHP/Apache/MySQL journey, and youve undoubtedly seen how JavaScript
code and other languages can be interspersed within the HTML code
in an HTML page. What makes PHP so different is that it not only
allows HTML pages to be created on the fly; it is invisible to your
Web site visitors. The only thing they see when they view the
source of your code is the resulting HTML output. This gives you
more security for your PHP code and more flexibility in writing
it.
HTML can also be written inside the PHP section of your page;
this allows you to format text while keeping blocks of code
together. This will also help you write organized, efficient code,
and the browser (and, more important, the viewer) wont know the
difference.
PHP can also be written as a standalone program, with no HTML at
all. This is helpful for storing your connection variables,
redirecting your visitors to another page of your site, or
performing other functions that we discuss in this book.
What is a PHP File?
PHP files can contain text, HTML tags and scripts PHP files are
returned to the browser as plain HTML PHP files have a file
extension of ".php", ".php3", or ".phtml"
How to write php code
One of the benefits of using PHP is that it is relatively simple
and straightforward. As with any computer language, there is
usually more than one way to perform the same function. Once you
feel comfortable writing some PHP programs, you can research
shortcuts to make yourself and your code more efficient. For the
sake of simplicity, we cover only the most common uses, rules, and
functions of PHP.
Data type and Variable
-
Build Bright University Faculty of Information and
Technology
page: 10
You should always keep in mind these two basic rules of PHP:
PHP is denoted in the page with opening and closing tags as
follows:
PHP lines end with a semicolon, generally speaking:
PHP Comments
Comments can be added to explain the JavaScript, or to make it
more readable. Single line comments start with //. Multi line
comments start with /* and end with */.
PHP Constants and Variables
Overview of constants
A constant is a placeholder for a value that you reference
within your code. Constants are typically named with capital
letters (so you can easily find them within your code), and the
values are usually formally defined before using them. Constant
names must begin with a letter or underscore and cannot begin with
a number. Names are also case-sensitive.
The values assigned to constants are defined with the PHP
function define(). Once theyve been defined, they cant be changed
or undefined.
Syntax:
Or
define(ConstantsName,Constans value);
-
Build Bright University Faculty of Information and
Technology
page: 11
Ex: first_prog.php
Result:
Overview of variables
Unlike constants, variables are obviously meant to be
variablethey are meant to change or be changed at some point in
your program. Variables also do not need to be defined or declared
and can simply be assigned when needed.
Variables are denoted with a dollar sign ($) and are not
case-sensitive as are constants.
Syntax:
Note: Variable Naming Rules
- A variable name must start with a letter or an underscore "_"
- A variable name can only contain alpha-numeric characters and
underscores - A variable name should not contain spaces. If a
variable name is more than one word, it should be separated with
underscore ($my_string), or with capitalization ($MyString)
Build Bright University
$variable_name=value;
-
Build Bright University Faculty of Information and
Technology
page: 12
Ex: first_prog.php
Result:
The Concatenation Operator
There is only one string operator in PHP. The concatenation
operator (.) is used to put two string values together.
Ex:
Build Bright University
-
Build Bright University Faculty of Information and
Technology
page: 13
The PHP Operators
Operators are symbols that you can use to manipulate values and
variables by performing an operation on them.
Arithmetic Operators
Arithmetic operators are straightforward; they are just the
normal mathematical operators. PHPs arithmetic operators are shown
in table below:
Operator Description Example Result
+ Addition x=2
x+2 4
-
Subtraction x=2 5-x
3
* Multiplication x=4
x*5 20
/ Division 15/5 5/2 3 2.5
% Modulus (division remainder) 5%2
10%8 10%2
1 2 0
++ Increment x=5
x++ x=6
--
Decrement x=5 x--
x=4
Assignment Operators
Youve already seen the basic assignment operator (=). Always
refer to this as the assignment operator and read it as is set
to.
Combination Assignment Operators
In addition to the simple assignment, there is a set of combined
assignment operators. Each of them is a shorthand way of performing
another operation on a variable and assigning the result back to
that variable.
Operator Example Is The Same As = x=y x=y
+= x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y
x=x.y
%= x%=y x=x%y
-
Build Bright University Faculty of Information and
Technology
page: 14
Comparison Operators
The comparison operators compare two values. Expressions using
these operators return either of the logical values true or false
depending on the result of the comparison.
Given that x=5, the table below explains the comparison
operators:
Operator Description Example = = is equal to x= =8 is false
= = = is exactly equal to (value and type) x= = =5 is true x= =
="5" is false
!= is not equal x!=8 is true > is greater than x>8 is
false < is less than x= is greater than or equal to x>=8 is
false
-
Build Bright University Faculty of Information and
Technology
page: 15
Chapter 3:
If you want to sensibly respond to your users input, your code
needs to be able to make decisions. The constructs that tell your
program to make decisions are called conditionals.
If Statement
You can use an if statement to make a decision. You should give
the if statement a condition to use. If the condition is true, the
following block of code will be executed. Conditions in if
statements must be surrounded by parentheses ( ).
Syntax:
Ex: if_statement.php
if.....else Statements
You may often need to decide not only whether you want an action
performed, but also which of a set of possible actions you want
performed.
An else statement allows you to define an alternative action to
be taken when the condition in an if statement is false. Say you
want to warn Bobs customers when they do not order anything. On the
other hand, if they do make an order, instead of a warning, you
want to show them what they ordered.
Syntax:
Control Structure
if (condition){ Block statement;
}
Test php
if (condition){ Statement to be execute if condition is true}
else{
Statement to be execute if condition is not true}
-
Build Bright University Faculty of Information and
Technology
page: 16
Ex: if_else.php
if.....else if Statements
For many of the decisions you make, you have more than two
options. You can create a sequence of many options using the else
if statement, which is a combination of an else and an if
statement. When you provide a sequence of conditions, the program
can check each until it finds one that is true.
Syntax:
Ex: if_elseif.php
if (condition){block statement1;} elseif (condition1) {block
statement 2;} elseif (condition2) {block statement 3;}
else{block n;}
-
Build Bright University Faculty of Information and
Technology
page: 17
switch Statements
The switch statement works in a similar way to the if statement,
but it allows the condition to take more than two values. In an if
statement, the condition can be either true or false. In a switch
statement, the condition can take any number of different values,
as long as it evaluates to a simple type (integer, string, or
float).You need to provide a case statement to handle each value
you want to react to and, optionally, a default case to handle any
that you do not provide a specific case statement for.
Syntax:
Ex:switch.php
switch (expression) { case label1: code to be executed if
expression = label1; break; case label2: code to be executed if
expression = label2; break; default: code to be executed if
expression is different from both label1 and label2; }
-
Build Bright University Faculty of Information and
Technology
page: 18
switch.php (continues)
case 6: echo "Number $x = Satureday"; break; default: echo
"Number $x = Sunday"; } ?>
-
Build Bright University Faculty of Information and
Technology
page: 19
Chapter 4:
Looping statements in PHP are used to execute the same block of
code a specified number of times.
Looping
Very often when you write code, you want the same block of code
to run a number of times. You can use looping statements in your
code to perform this.
In PHP we have the following looping statements:
while - loops through a block of code if and as long as a
specified condition is true do...while - loops through a block of
code once, and then repeats the loop as long as a special condition
is true. for - loops through a block of code a specified number of
times foreach - loops through a block of code for each element in
an array
The while Statement
The simplest kind of loop in PHP is the while loop. Like an if
statement, it relies on a condition. The difference between a while
loop and an if statement is that an if statement executes the
following block of code once if the condition is true. A while loop
executes the block repeatedly for as long as the condition is
true.
You generally use a while loop when you dont know how many
iterations will be required to make the condition true. If you
require a fixed number of iterations, consider using a for
loop.
Syntax:
Loop Structure
while (condition){ code to be executed;
}
-
Build Bright University Faculty of Information and
Technology
page: 20
Ex: while_loop.php
Result:
A while Statement
-
Build Bright University Faculty of Information and
Technology
page: 21
Create table with while loop: create_table_while.php
Result:
Distance Cost
-
Build Bright University Faculty of Information and
Technology
page: 22
The do while statement
A do..while loop differs from a while loop because the condition
is tested at the end. This means that in a do..while loop, the
statement or block within the loop is always executed at least
once.
Even if you consider this example in which the condition will be
false at the start and can never become true, the loop will be
executed once before checking the condition and ending
Syntax:
Ex1: do_while.php
Ex2:even_odd.php
do { code to be executed; } while (condition);
A while Statement
-
Build Bright University Faculty of Information and
Technology
page: 23
Result:
The for statement
The for statement is the most advanced of the loops in PHP.
In it's simplest form, the for statement is used when you know
how many times you want to execute a statement or a list of
statements.
Syntax:
Ex:for.php
for(init; cond; incr){ code to be execute; }
A while Statement
-
Build Bright University Faculty of Information and
Technology
page: 24
Result:
Ex2: table_bgcolor.php
The for loop statement
Alternating row colors
-
Build Bright University Faculty of Information and
Technology
page: 25
Result:
The foreach statement
The foreach statement is used to loop through arrays.
Syntax:
For every loop, the value of the current array element is
assigned to $value (and the array pointer is moved by one) - so on
the next loop, you'll be looking at the next element.
Ex:foreach.php
foreach ($array as $value) { code to be executed; }
-
Build Bright University Faculty of Information and
Technology
page: 26
Ex2:foreach_table.php
Result:
Read array value into table
-
Build Bright University Faculty of Information and
Technology
page: 27
Chapter 5:
Introduction
Weve talked about variables and how they are used, but what if
we had more than one value assigned to that variable? That, my
friends, is a good old-fashioned array. Arrays are nothing more
than lists of bits of information mapped with keys and stored under
one variable name. For example, you can store a persons name and
address or a list of states in one variable.
Whats array?
An array is a data structure that stores one or more similar
type of values in a single value. There are three different kinds
of arrays and each array value is accessed using an ID which is
called array index.
Numeric array - An array with a numeric index. Values are stored
and accessed in linear fashion Associative array - An array with
strings as index. This stores element values in association with
key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and
values are accessed using multiple indices.
Numeric Array
These arrays can store numbers, strings and any object but their
index will be pre-presented by numbers. By default array index
starts from zero.
Syntax:
Set string value into array: Ex: $name=array(Sok ,Chan, Nara,
Nary, Ratha); or $name[0]=Sok; $name[1]=Chan; $name[2]=Nara;
$name[3]=Nary; $name[4]=Ratha; Set string value into array: Ex:
$score=array(10,20,30,40,50);
PHP Array Objects
$names[key] = value; or $names =
array("value0","value1","value2");
-
Build Bright University Faculty of Information and
Technology
page: 28
Ex: num_array.php (first method to create array)
Result:
The Array Objects Using Numerically array
-
Build Bright University Faculty of Information and
Technology
page: 29
Ex: num_array1.php (second method to create array)
Result:
The Array Objects
Using Numerically array
-
Build Bright University Faculty of Information and
Technology
page: 30
Accessing Array Contents
To access the contents of a variable, you use its name. If the
variable is an array, you access the contents using the variable
name and an index. The index indicates which of the values in the
array you access. The index is placed in square brackets after the
name.
Ex: $numbers = array("one","two","three","four","five");
echo $numbers[2];// three
Using Loops to Access the Array Contents
Because the array is indexed by a sequence of numbers, you can
use a for loop to more easily display its contents:
Ex:
Associative Arrays
The associative arrays are very similar to numeric arrays in
term of functionality but they are different in terms of their
index. Associative array will have their index as string so that
you can establish a strong association between key and values.
Syntax:
Set string value into array: Ex: $name[firstname] = Sok;
$name[lastname] = San; or $name = array(firstname=>Sok,
lastname=>San);
Note: If you wanted to simply store a list and not worry about
the particular order, or what each value should be mapped to (such
as a list of states or flavors of shaved ice), you dont need to
explicitly name the keys and PHP will assign invisible internal
keys for processing. This would be set up as follows:
$array_name=("key0"=>"value0","key1"=>"value1",); or
$array_name["key"]= "value";
$numbers = array("one","two","three","four","five");
for($i=0;$i
-
Build Bright University Faculty of Information and
Technology
page: 31
Ex:asso_array.php
Associate Array
First method
-
Build Bright University Faculty of Information and
Technology
page: 32
Result:
Using Loops to Access the Array Contents
Because the indices in an array are not numbers, you cannot use
a simple counter in a for loop to work with the array. However, you
can use the foreach loop or the list( ) and each( ) constructs.
The foreach loop
The foreach loop has a slightly different structure when using
associative arrays. You can use it exactly as you did in the
previous example, or you can incorporate the keys as well:
Ex: foreach_ass.php Using foreach to access associative array
contents
-
Build Bright University Faculty of Information and
Technology
page: 33
Result:
each( ) construct
The following code lists the contents of the $prices array using
the each() construct:
Ex: each_ass.php
Using each() construct Using each() construct to access
associative
-
Build Bright University Faculty of Information and
Technology
page: 34
Result:
list( ) construct
There is a more elegant and more common way of doing the same
thing. The construct list( ) can be used to split an array into a
number of values. You can separate two of the values that the each(
) function gives you like this:
$salaries = array("sophal" => "500 $","sreyleak" => "300
$", "narry" => "100 $");
list( $employee, $value ) = each( $salaries);
This line uses each() to take the current element from $prices,
return it as an array, and make the next element current. It also
uses list() to turn the 0 and 1 elements from the array returned by
each() into two new variables called $employee and $value. You can
loop through the entire $value array, echoing the contents using
this short script:
$salaries = array("sophal" => "500 $","sreyleak" => "300
$", "narry" => "100 $");
while( list( $employee, $value )= each($salaries)) { echo
$employee - $value ;
}
-
Build Bright University Faculty of Information and
Technology
page: 35
Ex:list_ass.php
Result:
Using list() construct Using list() construct to access
associative
-
Build Bright University Faculty of Information and
Technology
page: 36
Multidimensional Arrays
A multi-dimensional array each element in the main array can
also be an array. And each element in the sub-array can be an
array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Ex:mul_array.php
Multidimensional Array Using Multidimensional Array
-
Build Bright University Faculty of Information and
Technology
page: 37
Result:
List of Array Functions
PHP: indicates the earliest version of PHP that supports the
function. Function Description
array( ) Create an array array_change_key_case( ) Returns an
array with all keys in lowercase or uppercase array_chunk( ) Splits
an array into chunks of arrays array_combine( ) Creates an array by
using one array for keys and another for its
values
array_count_values( )
Returns an array with the number of occurrences for each
value
array_diff( ) Compares array values, and returns the differences
array_diff_assoc( ) Compares array keys and values, and returns the
differences array_diff_key( ) Compares array keys, and returns the
differences array_diff_uassoc( ) Compares array keys and values,
with an additional user-made
function check, and returns the differences
array_diff_ukey( ) Compares array keys, with an additional
user-made function check, and returns the differences
array_fill( ) Fills an array with values array_fill_keys( ) Fill
an array with values, specifying keys array_filter( ) Filters
elements of an array using a user-made function array_flip( )
Exchanges all keys with their associated values in an array
-
Build Bright University Faculty of Information and
Technology
page: 38
array_intersect( ) Compares array values, and returns the
matches array_intersect_assoc( ) Compares array keys and values,
and returns the matches array_intersect_key( ) Compares array keys,
and returns the matches array_intersect_uassoc( ) Compares array
keys and values, with an additional user-made
function check, and returns the matches
array_intersect_ukey( ) Compares array keys, with an additional
user-made function check, and returns the matches
array_key_exists( ) Checks if the specified key exists in the
array array_keys( ) Returns all the keys of an array array_map( )
Sends each value of an array to a user-made function, which
returns new values
array_merge( ) Merges one or more arrays into one array
array_merge_recursive( ) Merges one or more arrays into one array
array_multisort( ) Sorts multiple or multi-dimensional arrays
array_pad( ) Inserts a specified number of items, with a specified
value, to an
array
array_pop( ) Deletes the last element of an array array_product(
) Calculates the product of the values in an array array_push( )
Inserts one or more elements to the end of an array array_rand( )
Returns one or more random keys from an array array_reduce( )
Returns an array as a string, using a user-defined function
array_reverse( ) Returns an array in the reverse order
array_search( ) Searches an array for a given value and returns the
key array_shift( ) Removes the first element from an array, and
returns the value of
the removed element
array_slice( ) Returns selected parts of an array array_splice(
) Removes and replaces specified elements of an array array_sum( )
Returns the sum of the values in an array array_udiff( ) Compares
array values in a user-made function and returns an
array
array_udiff_assoc( ) Compares array keys, and compares array
values in a user-made function, and returns an array
array_udiff_uassoc( ) Compares array keys and array values in
user-made functions, and returns an array
-
Build Bright University Faculty of Information and
Technology
page: 39
array_uintersect( ) Compares array values in a user-made
function and returns an array
array_uintersect_assoc( ) Compares array keys, and compares
array values in a user-made function, and returns an array
array_uintersect_uassoc( ) Compares array keys and array values
in user-made functions, and returns an array
array_unique( ) Removes duplicate values from an array
array_unshift( ) Adds one or more elements to the beginning of an
array array_values( ) Returns all the values of an array
array_walk( ) Applies a user function to every member of an array
array_walk_recursive( ) Applies a user function recursively to
every member of an array arsort( ) Sorts an array in reverse order
and maintain index association asort( ) Sorts an array and maintain
index association compact( ) Create array containing variables and
their values count( ) Counts elements in an array, or properties in
an object current( ) Returns the current element in an array each(
) Returns the current key and value pair from an array end( ) Sets
the internal pointer of an array to its last element extract( )
Imports variables into the current symbol table from an array
in_array( ) Checks if a specified value exists in an array key( )
Fetches a key from an array krsort( ) Sorts an array by key in
reverse order ksort( ) Sorts an array by key list( ) Assigns
variables as if they were an array natcasesort( ) Sorts an array
using a case insensitive "natural order" algorithm natsort( ) Sorts
an array using a "natural order" algorithm next( ) Advance the
internal array pointer of an array pos( ) Alias of current() prev(
) Rewinds the internal array pointer range( ) Creates an array
containing a range of elements reset( ) Sets the internal pointer
of an array to its first element rsort( ) Sorts an array in reverse
order
-
Build Bright University Faculty of Information and
Technology
page: 40
shuffle( ) Shuffles an array sizeof( ) Alias of count( ) sort( )
Sorts an array uasort( ) Sorts an array with a user-defined
function and maintain index
association
uksort( ) Sorts an array by keys using a user-defined function
usort( ) Sorts an array by values using a user-defined function
-
Build Bright University Faculty of Information and
Technology
page: 41
Chapter 6:
PHP Function
PHP functions are similar to other programming languages. A
function is a piece of code which takes one more input in the form
of parameter and does some processing and returns a value.
Functions exist in most programming languages; they separate
code that performs a single, well-defined task. This makes the code
easier to read and allows you to reuse the code each time you need
to perform the same task.
What is function?
A function is a block of code that can be executed whenever we
need it.
Creating PHP functions:
All functions start with the word "function()" Name the function
- It should be possible to understand what the function does by its
name. The name can start with a letter or underscore (not a number)
Add a "{" - The function code starts after the opening curly brace
Insert the function code Add a "}" - The function is finished by a
closing curly brace
Syntax:
Note: There are two parts which should be clear to you:
Creating a PHP Function Calling a PHP Function
PHP Function
function function_name($Argument1,$Argument2) { block
statements; }
-
Build Bright University Faculty of Information and
Technology
page: 42
Ex: show_msg.php
Naming Your Function:
The most important point to consider when naming your functions
is that the name should be short but descriptive.
A few restrictions follow:
Your function cannot have the same name as an existing function.
Your function name can contain only letters, digits, and
underscores. Your function name cannot begin with a digit.
Many languages do allow you to reuse function names. his feature
is called function overloading. However, PHP does not support
function overloading, so your function cannot have the same name as
any built-in function or an existing user-defined function. Note
that although every PHP script knows about all the built-in
functions, user-defined functions exist only in scripts where they
are declared. his means that you could reuse a function name in a
different file, but this would lead to confusion and should be
avoided.
The following function names are legal:
name() name2() name_three() _namefour()
These names are illegal: 5name() name-six() fopen()
.::Hypertext Proprocessor Function.
-
Build Bright University Faculty of Information and
Technology
page: 43
Note that although $name is not a valid name for a function, a
function call like
$name( );
May well execute, depending on the value of $name. The reason is
that PHP takes the value stored in $name, looks for a function with
that name, and tries to call it for you. This type of function is
referred to as a variable function and may occasionally be useful
to you.
Using Parameters
To do their work, most functions require one or more parameters.
A parameter allows you to pass data into a function. Here is a
sample function that requires a parameter; it takes a
one-dimensional array and displays it as a table:
Ex: getdata_into_table.php
If you call the create_table( ) function
function create_table($data) { echo ""; reset($data); //Remember
this is used to point to the beginning $value = current($data);
while ($value) { echo "$value\n"; $value = next($data); } echo "";
}
$my_array = array('Line one.','Line two.','Line three.');
create_table($my_array);
-
Build Bright University Faculty of Information and
Technology
page: 44
Summary code:
Result:
Function with Parameter
-
Build Bright University Faculty of Information and
Technology
page: 45
Ex: sum_func.php
Result:
.:: Function with parameter Function with Parameter
-
Build Bright University Faculty of Information and
Technology
page: 46
Returning from Functions
The keyword return stops the execution of a function. When a
function ends because either all statements have been executed or
the keyword return is used, execution return is to the statement
after the function call.
Ex:test_return.php
Result:
Returning from function
-
Build Bright University Faculty of Information and
Technology
page: 47
Obviously, this is not a very useful way to use return.
Normally, you want to return from the middle of a function only in
response to a condition being met.
An error condition is a common reason to use a return statement
to stop execution of a function before the end. If, for instance,
you write a function to find out which of two numbers is greater,
you might want to exit if any of the numbers are missing:
Ex2: larger.php
Returning from function
-
Build Bright University Faculty of Information and
Technology
page: 48
Result:
Returning Values from Functions
Exiting from a function is not the only reason to use return.
Many functions use return statements to communicate with the code
that called them. Instead of echoing the result of the comparison
in the larger() function, the function might have been more useful
if it returned the answer. This way, the code that called the
function can choose if and how to display or use it. The equivalent
built-in function max() behaves in this way.
Ex: You can write the larger() function as follows:
(larger1.php)
Returning value from function
-
Build Bright University Faculty of Information and
Technology
page: 49
Result:
Ex3: resturn_sum_func.php
Result:
Returning value from function
-
Build Bright University Faculty of Information and
Technology
page: 50
Chapter 7:
Overview
Using forms in a web based application is very common. Most
forms are used to gather information like in a signup form, survey
/ polling, guestbook, etc.
A form can have the method set as post or get. When using a form
with method = "post" you can use $_POST to access the form values.
And when the form is using method = "get" you can use $_GET to
access the values. The $_REQUEST super global can be used to access
form values with method="post" and method="get" but it is
recommended to use $_POST or $_GET instead so you will know from
what method did the values come from.
The GET method
The GET method sends the encoded user information appended to
the page request. The page and the encoded information are
separated by the ? character.
The GET method produces a long string that appears in your
server logs, in the browser's Location: box. The GET method is
restricted to send upto 1024 characters only. Never use GET method
if you have password or other sensitive information to be sent to
the server. GET can't be used to send binary data, like images or
word documents, to the server. The data sent by GET method can be
accessed using QUERY_STRING environment variable. The PHP provides
$_GET associative array to access all the sent information using
GET method.
PHP Forms
http://www.test.com/index.htm?name1=value1&name2=value2
-
Build Bright University Faculty of Information and
Technology
page: 51
Ex: post_method.php
Using Method Get
-
Build Bright University Faculty of Information and
Technology
page: 52
Result:
After submit:
There are a few disadvantages to passing variables through a
URL:
Everyone can see the values of the variables, so passing
sensitive information isnt really very secure using this
method.
The user can change the variable value in the URL, leaving your
site potentially open to showing something youd rather not
show.
A user might also pull up inaccurate or old information using a
saved URL with older variables embedded in it.
-
Build Bright University Faculty of Information and
Technology
page: 53
The POST method
The POST method transfers information via HTTP headers. The
information is encoded as described in case of GET method and put
into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be
sent. The POST method can be used to send ASCII as well as binary
data. The data sent by POST method goes through HTTP header so
security depends on HTTP protocol. By using Secure HTTP you can
make sure that your information is secure. The PHP provides $_POST
associative array to access all the sent information using GET
method.
Ex:post_method.php
Using Method Get
-
Build Bright University Faculty of Information and
Technology
page: 54
Result:
After submit:
-
Build Bright University Faculty of Information and
Technology
page: 55
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET,
$_POST, and $_COOKIE. We will discuss $_COOKIE variable when we
will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from
form data sent with both the GET and POST methods.
Ex: request_variable.php
Using Method Get
-
Build Bright University Faculty of Information and
Technology
page: 56
Result:
After submit:
-
Build Bright University Faculty of Information and
Technology
page: 57
Using Array as form elements values
You can get value from form elements by using array to store the
values.
Ex: array_with_form.php
Using Array as Form Value. Select the programming languages you
can use C++ Java PHP ASP Delphi
-
Build Bright University Faculty of Information and
Technology
page: 58
Result:
After submit:
-
Build Bright University Faculty of Information and
Technology
page: 59
Chapter 8:
The PHP date() function is used to format a time and/or
date.
The PHP Date( ) Function
The PHP date() function formats a timestamp to a more readable
date and time.
A timestamp is a sequence of characters, denoting the date
and/or time at which a certain event occurred.
Syntax:
Parameter Description format Required. Specifies the format of
the timestamp timestamp Optional. Specifies a timestamp. Default is
the current date and time
Ex: date.php
Result:
PHP Date Function
date(format,timestamp);
Using Data Function
-
Build Bright University Faculty of Information and
Technology
page: 60
Date( ) - Format the Date
The required format parameter in the date() function specifies
how to format the date/time.
The following characters are recognized in the format parameter
string:
format character Description
Example returned values
Day --- --- d Day of the month, 2 digits with leading zeros 01
to 31 D A textual representation of a day, three letters Mon
through Sun j Day of the month without leading zeros 1 to 31 l
(lowercase) A full textual representation of the day of the week
Sunday through Saturday
N ISO-8601 numeric representation of the day of the week (added
in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters
st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday)
through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365 Week ---
---
W ISO-8601 week number of year, weeks starting on Monday (added
in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Month --- ---
F A full textual representation of a month, such as January or
March January through December
m Numeric representation of a month, with leading zeros 01
through 12 M A short textual representation of a month, three
letters Jan through Dec n Numeric representation of a month,
without leading zeros 1 through 12 t Number of days in the given
month 28 through 31
Year --- ---
L Whether it's a leap year 1 if it is a leap year, 0
otherwise.
o
ISO-8601 year number. This has the same value as Y, except that
if the ISO week number (W) belongs to the previous or next year,
that year is used instead. (added in PHP 5.1.0)
Examples: 1999 or 2003
Y A full numeric representation of a year, 4 digits Examples:
1999 or 2003
y A two digit representation of a year Examples: 99 or 03 Time
--- ---
-
Build Bright University Faculty of Information and
Technology
page: 61
a Lowercase Ante meridiem and Post meridiem am or pm A Uppercase
Ante meridiem and Post meridiem AM or PM B Swatch Internet time 000
through 999 g 12-hour format of an hour without leading zeros 1
through 12 G 24-hour format of an hour without leading zeros 0
through 23 h 12-hour format of an hour with leading zeros 01
through 12 H 24-hour format of an hour with leading zeros 00
through 23 i Minutes with leading zeros 00 to 59 s Seconds, with
leading zeros 00 through 59
-
Build Bright University Faculty of Information and
Technology
page: 62
Chapter 9:
1. What is MySQL?
MySQL is an open source Relational Database Management System
(RDBMS) based around the Structured Query Language (SQL). In short,
MySQL is software that allows you to manage your databases.
The data in MySQL is stored in database objects called tables. A
table is a collection of related data entries and it consists of
columns and rows.
Database File: This is your main file that encompasses the
entire Database and that is saved to your hard-drive or floppy
disk.
Table: A table is a collection of data about a specific topic.
There can be multiple tables in a database.
Field: Fields are the different categories within a Table.
Tables usually contain multiple fields.
Datatypes: Datatypes are the properties of each field. A field
only has 1 datatype.
There are three main types: text, numbers, and Dates/Times.
TEXT TYPES
CHAR( ) A fixed section from 0 to 255 characters long. VARCHAR(
) A variable section from 0 to 255 characters long. TINYTEXT A
string with a maximum length of 255 characters. TEXT A string with
a maximum length of 65535 characters. BLOB A string with a maximum
length of 65535 characters. MEDIUMTEXT A string with a maximum
length of 16777215 characters. MEDIUMBLOB A string with a maximum
length of 16777215 characters. LONGTEXT A string with a maximum
length of 4294967295 characters. LONGBLOB A string with a maximum
length of 4294967295 characters.
The ( ) brackets allow you to enter a maximum number of
characters will be used in the Column.
CHAR and VARCHAR are the most widely used types. CHAR is a fixed
length string and is mainly used when the data is not going to vary
much in it's length. VARCHAR is a variable length string and is
mainly used when the data may vary in length.
CHAR may be faster for the database to process considering the
fields stay the same length down the column. VARCHAR may be a bit
slower as it calculates each field down the column, but it saves on
memory space. Which one to ultimately use is up to you.
Using both a CHAR and VARCHAR option in the same table, MySQL
will automatically change the CHAR into VARCHAR for compatibility
reasons.
MySQL Database
Database File
Tables
Field
Data type
Value
-
Build Bright University Faculty of Information and
Technology
page: 63
BLOB stands for Binary Large Object. Both TEXT and BLOB are
variable length types that store large amounts of data. They are
similar to a larger version of VARCHAR. These types can store a
large piece of data information, but they are also processed much
slower.
NUMBER TYPES
TINYINT( ) -128 to 127 normal 0 to 255 UNSIGNED.
SMALLINT( ) -32768 to 32767 normal 0 to 65535 UNSIGNED.
MEDIUMINT( ) -8388608 to 8388607 normal 0 to 16777215
UNSIGNED.
INT( ) -2147483648 to 2147483647 normal 0 to 4294967295
UNSIGNED.
BIGINT( ) -9223372036854775808 to 9223372036854775807 normal 0
to 18446744073709551615 UNSIGNED.
FLOAT A small number with a floating decimal point. DOUBLE( , )
A large number with a floating decimal point. DECIMAL( , ) A DOUBLE
stored as a string , allowing for a fixed decimal point.
The integer types have an extra option called UNSIGNED.
Normally, the integer goes from an negative to positive value.
Using an UNSIGNED command will move that range up so it starts at
zero instead of a negative number.
DATE TYPES
DATE YYYY-MM-DD. DATETIME YYYY-MM-DD HH:MM:SS. TIMESTAMP
YYYYMMDDHHMMSS. TIME HH:MM:SS.
2. Column Modifiers A column modifier is an extra add on command
to help the database organize and work better.
As mentioned on the previous page, the integer types have an
extra option called UNSIGNED. Normally, the integer goes from an
negative to positive value. Using an UNSIGNED command will move
that range up so it starts at zero instead of a negative
number.
Modifier commands are: INDEX, UNIQUE, PRIMARY KEY,
AUTO_INCREMENT, NULL, NOT NULL, DEFAULT, BINARY, and ZEROFILL.
Indexing: is a way to improve a database performance. You are
telling the database that THIS
specific column is special and may help organize the data. If
there is a column you will be referring to often, it would probably
be the best to be an INDEX column.
An INDEX column may have more than one cell holding the same
data value. The two other index types are UNIQUE and PRIMARY KEY.
UNIQUE states that each cell in the column should have a unique
value. PRIMARY KEY is a special variety of the UNIQUE command.
-
Build Bright University Faculty of Information and
Technology
page: 64
The AUTO_INCREMENT modifier works on any of the integer types.
Each time a new row is added into the database table, the number in
this column will appear and automatically increase by one from the
previous row.
NULL: is no value. It is not space, it is not zero. A majority
of the time you will want to specify
a field to be NOT NULL so that any blank entries will be
considered as "something".
DEFAULT: will assign a default value to a cell if nothing is
entered for the value. It will work on most data types except BLOB
and TEXT.
BINARY: is used with CHAR and VARCHAR types. It causes the
values to be treated as "binary strings" making them Case
Sensitive.
ZEROFILL: is used with numeric data types. It will display
leading zeros of a number based on the display width.
3. Working with SQL Command
3.1 How to create database on MYSQL server
Ex: create database managestudent; 3.2 How to show database
3.3 How to change database
3.4 How to delete database
Ex: DROP tblstudents; 3.4 How to create table
Ex: CREATE TABLE students( id int( 6 ) NOT NULL auto_increment,
name text, sex char( 6 ) , dob date, );
CREATE DATABASE [database-name];
SHOW DATABASES;
USE [database-name];
DROP database-name;
CREATE TABLE table-name (field1 datatype, field2 datatype,);
-
Build Bright University Faculty of Information and
Technology
page: 65
3.5 How to delete table
Ex: DROP TABLE tblstudent; 3.6 How to rename table
3.7 How to show table on database
3.8 How to view table structure
Ex: EXPLAIN tblstudents; 3.9 How to modify table structure
a) Add new field
Ex: ALTER TABLE tblscore ADD COLUMN maxscore int(2); b) Delete
column of table
c) Change column name
d) Modify column on table
4. Working with SQL statements a) Insert statement
ex: INSERT INTO tblstudents(id,name,sex,dob)
VALUES(001,dara,male,1984-12-20); INSERT INTO
tblstudents(id,name,sex,dob)
VALUES(002,vantha,male,1984-12-20), (003,raksa,female, 1984-
12-20);
DROP TABLE [table-name];
EXPLAIN [table-name]; or DESCRIBE [table-name];
ALTER TABLE [table-name] ADD COLUMN [new-field-name]
datatype;
ALTER TABLE [table-name] DROP [field-name];
RENAME TABLE [old-table-name] TO [new-table-name]; or ALTER
TABLE [old-table-name] RENAME TO [new-table-name];
ALTER TABLE [table-name] CHANGE [old-column] [new-column]
datatype;
ALTER TABLE [table-name] MODIFY [column-name] datatype;
SHOW TABLES;
INSERT INTO [table-name] (field1, field2,..) VALUES
(value1,value2,..); INSERT INTO [table-name] (field1, field2,..)
SELECT (field1,field2,.);
-
Build Bright University Faculty of Information and
Technology
page: 66
b) Select statement
Ex: SELECT colA, colB FROM mytable; SELECT colA, colB FROM
mytable WHERE colA= condition;
c) Delete Statement
Ex: DELETE FROM tblstudents WHERE studentid=001;
d) Update Statement
Ex: UPDATE tblstudent SET dob=1980-11-21 WHERE
studentid=001;
SELECT [ALL | DISTINCT | DISTINCTROW] [Select expression ..]
FROM [tables] WHERE [condition] GROUP BY [column name] HAVING
[where condition] ORDER BY {column name} [ASC | DESC] LIMIT
{[offset,] row_count};
DELETE FROM table-name WHERE condition;
UPDATE table-name SET column-name= WHERE condition;
-
Build Bright University Faculty of Information and
Technology
page: 67
Chapter 10:
1. How to connect to php with mysql database server?
Before you can access data in a database, you must create a
connection to the database. In PHP, this is done with the
mysql_connect() function.
Syntax:
Parameters: servername: is the name if IP address of server that
contain Mysql server. username: is the username of Mysql server.
password: is the password to log in.
Ex:connect.php
a) How to close connection
Ex:close_connect.php
PHP MySQL Database Connection
mysql_connect(servername,username,password);
mysql_close($connection);
-
Build Bright University Faculty of Information and
Technology
page: 68
b) How to select database
Ex: select_database.php
c) How to manipulate data from php with mysql
This function is used to execute SQL command
How to insert data into Mysql When data is put into a MySQL
table it is referred to as inserting data. When inserting data
it is important to remember the exact names and types of the
table's columns.
Ex: insertdata.php
Field Name Data type id int(3) name varchar(50) sex varchar(7)
dob date
mysql_select_db();
mysql_query(sql statement);
tblstudents
-
Build Bright University Faculty of Information and
Technology
page: 69
How select data from Mysql
There are two functions to select data from Mysql table.
Syntax:
Execute query string.
- mysql_fetch_row(query string); - mysql_fetch_array(query
string);
-
Build Bright University Faculty of Information and
Technology
page: 70
Ex: select a record from database.
Ex: select all records from database.
-
Build Bright University Faculty of Information and
Technology
page: 71
Chapter 11:
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small
file that the server embeds on the user's computer. Each time the
same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie
values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the tag.
Syntax:
Ex1: In the example below, we will create a cookie named "user"
and assign the value "Alex Porter" to it. We also specify that the
cookie should expire after one hour:
Ex: cookie.php
Note: The value of the cookie is automatically URLencoded when
sending the cookie, and automatically decoded when received (to
prevent URLencoding, use setrawcookie() instead).
PHP cookies and sessions
setcookie(name, value, expire, path, domain);
.....
-
Build Bright University Faculty of Information and
Technology
page: 72
Ex2: You can also set the expiration time of the cookie in
another way. It may be easier than using seconds.
cookie2.php
In the example above the expiration time is set to a month (60
sec * 60 min * 24 hours * 30 days).
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie
value.
In the example below, we retrieve the value of the cookie named
"user" and display it on a page:
read_cookie.php
In the following example we use the isset() function to find out
if a cookie has been set:
isset_cookie.php
.....
-
Build Bright University Faculty of Information and
Technology
page: 73
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration
date is in the past.
Ex: delete_cookie.php
PHP Sessions
A PHP session variable is used to store information about, or
change settings for a user session. Session variables hold
information about one single user, and are available to all pages
in one application.
PHP Session Variables
When you are working with an application, you open it, do some
changes and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web
server does not know who you are and what you do because the HTTP
address doesn't maintain state.
A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping
items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a
permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and
store variables based on this UID. The UID is either stored in a
cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you
must first start up the session.
Note: The session_start() function must appear BEFORE the
tag:
-
Build Bright University Faculty of Information and
Technology
page: 74
Ex1: session.php
The code above will register the user's session with the server,
allow you to start saving user information, and assign a UID for
that user's session.
Storing a Session Variable
The correct way to store and retrieve session variables is to
use the PHP $_SESSION variable:
Ex1: set-read-session.php
In the example below, we create a simple page-views counter. The
isset() function checks if the "views" variable has already been
set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to
1:
-
Build Bright University Faculty of Information and
Technology
page: 75
Ex2: isset-session.php
Destroying a Session
If you wish to delete some session data, you can use the unset()
or the session_destroy() function.
The unset() function is used to free the specified session
variable:
Ex:delete_session.php
You can also completely destroy the session by calling the
session_destroy() function:
Note: session_destroy() will reset your session and you will
lose all your stored session data.
-
Build Bright University Faculty of Information and
Technology
page: 76
Chapter 12:
Server Side Includes (SSI)
You can insert the content of one PHP file into another PHP file
before the server executes it, with the include() or require()
function.
The two functions are identical in every way, except how they
handle errors:
include() generates a warning, but the script will continue
execution require() generates a fatal error, and the script will
stop
These two functions are used to create functions, headers,
footers, or elements that will be reused on multiple pages.
Server side includes saves a lot of work. This means that you
can create a standard header, footer, or menu file for all your web
pages. When the header needs to be updated, you can only update the
include file, or when you add a new page to your site, you can
simply change the menu file (instead of updating the links on all
your web pages).
PHP include() Function
The include() function takes all the content in a specified file
and includes it in the current file. If an error occurs, the
include() function generates a warning, but the script will
continue execution.
Ex: Assume that you have a standard header file, called
"header.php". To include the header file in a page, use the
include() function:
PHP Include and Require
Welcome to my home page! Some text.
-
Build Bright University Faculty of Information and
Technology
page: 77
Ex2: Assume we have a standard menu file, called "menu.php",
that should be used on all pages:
All pages in the Web site should include this menu file. Here is
how it can be done:
PHP require() Function
The require() function is identical to include(), except that it
handles errors differently.
If an error occurs, the include() function generates a warning,
but the script will continue execution. The require() generates a
fatal error, and the script will stop.
Error Example include() Function
Home Tutorials References Examples About Us Contact Us
Welcome to my home page. Some text.
-
Build Bright University Faculty of Information and
Technology
page: 78
Error message:
Notice: that the echo statement is executed! This is because a
Warning does not stop the script execution.
Error Example require() Function
Now, let's run the same example with the require() function.
Error message:
The echo statement is not executed, because the script execution
stopped after the fatal error.
It is recommended to use the require() function instead of
include(), because scripts should not continue after an error.
Warning: include(wrongFile.php) [function.include]: failed to
open stream: No such file or directory in C:\home\website\test.php
on line 5
Warning: include() [function.include]: Failed opening
'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in
C:\home\website\test.php on line 5
Warning: require(wrongFile.php) [function.require]: failed to
open stream: No such file or directory in C:\home\website\test.php
on line 5
Fatal error: require() [function.require]: Failed opening
required 'wrongFile.php' (include_path='.;C:\php5\pear') in
C:\home\website\test.php on line 5
-
Build Bright University Faculty of Information and
Technology
page: 79
Reference Book
Julie C. Meloni (2000), PHP Fast & Easy Web Development,
Prentice-Hall of India.
Bill McCarty (2001), PHP4: A Beginners Guide,
Osborne/McGraw-Hill