0% found this document useful (0 votes)
39 views201 pages

WT UNIT-IV

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views201 pages

WT UNIT-IV

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 201

WEB TECHNOLOGIES

UNIT-IV
SYLLABUS
Introduction to PHP: The problem with other Technologies (Servlets
and JSP), Downloading, installing, configuring PHP, Programming in a
Web environment and The anatomy of a PHP Page. Overview of PHP .
Data types and Concepts: Variables and data types, Operators,
Expressions and Statements, Strings, Arrays and Functions.

PHP Advanced Concepts: Using Cookies, Using HTTP Headers, Using


Sessions, Authenticating users, Using Environment and Configuration
variables, Working with Date and Time.
Server-side Programming :
It is the program that runs on server dealing with the generation of
content of web page.
1) Querying the database
2) Operations over databases
3) Access/Write a file on server.
4) Interact with other servers.
5) Structure web applications.
6) Process user input
The problem with other Technologies:
Servlets:
• Servlet is a class that is defined in javax.servlet package.
• There are two types of servlets called GenericServlet, and HTTPServlet.
• Any application class which will be defined should extend Generic or
HTTPServlet.
• Some methods like service(), doGet(),doPost() should be overridden in
sub class to achieve desired business logic.
• Hence, Servlets are used to provide Business logic for any application.
Problems with Servlets:
1) Servlets are difficult to implement business logic compare with
PHP.
2) Servlets execution is slow compared to PHP.
3) Servlet should interact with Server for every client request.
4) Servlet can handle new request only after destroying old request /
current request.
5) If any modification is necessary, the programmer must update the
change, and compile it again to see modified effect where as in PHP,
Browser update the output automatically after saving the change in
the PHP program.
6) Servlets errors are difficult to handle.
7) Every Servlet must have XML mapping constraint.
Java Server Pages(JSP):
 JSP is one of scripting language used to design web pages.
 It is tag based language because every statement must be specified in
tags.
 Every tag must have starting and ending symbol %.
Problems wih JSP:
1) Every JSP program is first converted into Servlet Program although it
used at server side.
2) It is difficult to understand JSP program and to write statements.
3) It is compiled server side language where as PHP is server side interpreting
language.
4) It can support only minimal web servers.
5) JSP also very difficult to handle errors that were raised in it.
6) JSP use Java Technology where as PHP is independent of Java
Technology.
What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use.
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the
browser as plain HTML.
• PHP files have extension ".php“.
What Can PHP Do?

• PHP can generate dynamic page content.


• PHP can create, open, read, write, delete, and close files on the
server.
• PHP can collect form data.
• PHP can send and receive cookies.
• PHP can add, delete, modify data in your database.
• PHP can be used to control user-access.
• PHP can encrypt data.
Why PHP?
 PHP runs on various platforms
(Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS,
etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side.
Introduction to PHP:
1. PHP, or PHP: Hypertext Preprocessor, has become the most popular
server-side scripting language for creating dynamic web pages.
2. PHP is an open-source technology that’s supported by a large community
of users and developers.
3. PHP is platform independent—implementations exist for all major
UNIX, Linux, Mac and Windows operating systems.
4. PHP also supports many databases, including MySQL.

5. PHP supports a large number of major protocols such as POP3, IMAP,


LDAP.
CHARACTERISTICS OF PHP
Five important characteristics make PHP's practical nature
possible:
1. Simplicity
2. Efficiency
3. Security
4. Flexibility
5. Familiarity
Features of PHP:
 PERFORMANCE: Script written in PHP executes much faster
then those scripts written in other languages such as JSP & ASP.
 OPEN SOURCE SOFTWARE: PHP source code is free
available on the web, you can developed all the version of PHP
according to your requirement without paying any cost.
 PLATFORM INDEPENDENT: PHP are available for
WINDOWS, MAC, LINUX & UNIX operating system.
A PHP application developed in one OS can be easily
executed in other OS also.
Compatibility: PHP is compatible with almost all local servers used
today like Apache, IIS etc.

Embedded: PHP code can be easily embedded within HTML tags


and script.
TOPIC-3

DOWNLOADING, INSTALLING AND CONFIGURING PHP:


1) Downloading PHP: The PHP product available in site named
http://www.php.net/download.php.
2) Installing and Configuring of PHP:
a) Installation: This requires first to install XAMPP server. Installation of
XAMPP is as follows.
1) Click on XAMPP installation file i.e XAMP-win32-1.7.2
2) Select the location to install Xampp server files in the hard disk by
clicking browse button.
3) XAMPP related files were all loaded into XAMPP directory in C
drive.

4) Click on XAMPP-control file to start the server.

5) Open the browser and type localhost in the address bar of the
browser, then press enter.

6) Home page of XAMPP server appears on the web page.


b) Configuring:
Step1:
The configuration of PHP can be done using control panel application in the
PHP server. It provides different services to manage and configure PHP.
Step2:
The PHP files must be saved in C:/XAMPP/htdocs directory.
Step3:
MySQL database is configured on PhpMyAdmin service.

Step4:
For testing PHP Application, type the following URL in the browser and
press enter. http://localhost/phpfilename.php where phpfilename is name
of PHP file.
Test your installation
PROGRAMMING IN WEB ENVIRONMENT:
 Web development is a broad term for the work involved in
developing a web site for the Internet (World Wide Web) or an
intranet (a private network).
Web development can range from developing the simplest static
single page of plain text to the most complex web-based internet
applications, electronic businesses, and social network services.
 Among web professionals, "web development" usually refers to
the main non-design aspects of building web sites: writing markup
and coding (scripting).
Web Development can be split into many areas and a typical and
basic web development hierarchy might consist of:
1. Client side coding
2. Server side coding
Client side coding:
The nature of client side coding allows you to alter the HTML on a local
client and refresh the pages with updated. If a server side script accepts
content from a locally modified client side script, the web development of
that page is poorly sanitized with relation to security.
With the help of client side programming or coding we can do the
following:
1. Make interactive WebPages.
2. Make stuff happen dynamically on the web page.
3. Interact with temporary storage and local storage (cookies, local storage)
4. Sends request to server and retrieve data from it.
Some of the client side languages are :

1. Java script (essentially the client side scripting languages)

2. Ajax (used for implementing java script & XML without


effecting the web page itself)

3. HTML & CSS


Server side coding:

Server-side programming is the general name for the kinds of


programs which are run on the Server. With the help of server
side programming or coding we can do the following:

1. Process user input.


2. Display pages.
3. Structure web applications.
4. Interact with permanent storage (SQL, files).
Server-side scripting is a technique used in website
design which involves embedding scripts in an HTML
source code.
Some of the server side languages are:-

1. JSP
2. PHP
3. ASP
ANATOMY OF PHP:

The PHP anatomy can be specified through <?php ?>.


The php tag is written in body tag of HTML tag.
The PHP tag specifies all the code within starting and ending ?.
A Html program can contain any number of PHP tags. All those
PHP tags are executed in same browser.
 A PHP file can contain text, tags, and scripts.
The PHP program can be saved with extension .php, .php3
or .phtml.
When a web server encounters this extension in a requested
file, it automatically passes it to the PHP processor
The PHP file can be executed on any operating system.
.
The following is the PHP Tag syntax:

<?php
//php statements
?>
Short Tags:
For less motivated typists, even shorter delimiter syntax is
available. Known as short-tags, this syntax forgoes the php
reference required in the default syntax, you may also
encounter code where the opening and closing syntax used is
like this:
<?
statements…
?>
Comments:

<?php
// This is a single-line comment

# This is also a single-line comment


?>

<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
VARIABLES:
• Variable is used to store information.
• In PHP developer is not forced to assign a given variable a data
type and then assign a value to it.
• Instead, PHP automatically assigns a data type to a variable when
a value is allocated to it. This makes PHP is simple to use.
• PHP variable follows certain rules like identifiers .
All variables must begin with a $ and must be immediately followed by
a letter or an underscore
 Variables in PHP are indeed case sensitive and can contain any number
of letters, numbers, or underscores after the initial $ and first letter or
underscore.
A variable name should not contain spaces. If a variable name is more
than one word, it should be separated with an underscore ($my_string),
or with capitalization ($myString).
Variables are assigned by a value in the versions earlier to PHP4.
 Later in PHP4 and PHP5 we can assign variables by reference.
Uninitialized variables have a default value

• Booleans default to FALSE,


• Integers and floats default to zero,
• Strings (e.g. used in echo()) are set as an empty string
• Arrays become to an empty array.
Variable Declaration

• A variable always begins with a dollar sign, $.


• Variable names follow the same naming rules as identifiers.
That is, a variable name can begin with either a letter or an
underscore and can consist of letters, underscores, numbers, or
other ASCII characters ranging from 127 through 255.

• The following are all valid variables:


$color $operating_system $_some_variable
• As variables are case sensitive, the following variables have no
relation:
$color $Color $COLOR

• Two methodologies are available for variable assignment:


by value and by reference.
Value Assignment

• Assignment by value simply involves copying the value of the assigned


expression to the variable assignee , which is the most common type of
assignment.
Ex:
$color = "red";
$number = 12;
$age = 12;
$sum = 12 + "15";
Ex:

<html>
<body>
<?php
$x = 5;
$y = 500;
echo $x + $y;
?>
</body>
</html>
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable
can be referenced/used.

PHP has three different variable scopes:


• local
• global
• static
A variable declared outside a function has a GLOBAL SCOPE and
can only be accessed outside a function:

Output:
•A variable declared within a function has a LOCAL
SCOPE and can only be accessed within that function:
Output:
Global keyword:
The global keyword is used to access a global variable from
within a function.
To do this, use the global keyword before the variables
(inside the function):
15
Static Keyword:
• Normally, when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a local
variable NOT to be deleted. We need it for a further job.
• To do this, use the static keyword when you first declare the
variable:
Output:
PHP’s Supported Datatypes:
A datatype is the generic name assigned to any data sharing a
common set of characteristics.

Common datatypes include Boolean, integer, float, string, and


array.

PHP supports eight primitive data types with three


classifications.
Scalar Data types: Boolean, integer, float, and string

Compound data types: array and object

Special data types: resource and NULL


1. Scalar Data type:

 Scalar data types are used to represent a single value.


 Several data types fall under this category, including Boolean,
integer, float, and string.

 PHP supports Four Scalar Data types such as Boolean, integer,


float and string.
(i) Boolean:
 The Boolean data type represents truth, supporting only two
values: TRUE and FALSE (case insensitive).
 Alternatively, you can use zero to represent FALSE, and any
nonzero value to represent TRUE.
Ex: $var = false; // $var is false.
$var = 1; // $var is true.
$var = -1; // $var is true.
$var = 5; // $var is true.
$var = 0; // $var is false.
(ii) Integer:
An integer is representative of any whole number or, in other
words, a number that does not contain fractional parts.
 PHP supports integer values represented in base 10 (decimal),
base 8 (octal), and base 16 (hexadecimal) numbering systems.
EXAMPLES:-
42 // decimal
-678900 // decimal
0755 // octal
0xC4E // hexadecimal
(iii) Float:
 Floating-point numbers, also referred to as floats, doubles, or real
numbers, allow you to specify numbers that contain fractional parts.
 Floats are used to represent monetary values, weights, distances,
and a whole host of other representations in which a simple integer
value won‘t suffice.
Examples: 4.5678
4.0
8.7e4
1.23E+11
(iv) String:
 A string is a sequence of characters treated as a contiguous
group. Strings are delimited by single or double quotes.
Examples:
"PHP is a great language"
'*9subway\n'
"123$%^789"
PHP treats strings in the same fashion as arrays.
Example: $color = "maroon";
$parser = $color[2]; // Assigns 'r' to $parser
Output:
2 Compound Datatypes:
Compound datatypes allow for multiple items of the same
type to be aggregated under a single representative entity.
The array and the object fall into this category

(i) Array: An array is an indexed collection of data values. Each


member of the array index (also known as the key) references a
corresponding value.

Example: $sub [0] = “WIT”;


$sub[1] = “DP”;
OUTPUT
(ii) Object:
 The other compound datatype supported by PHP is the object.
 The object is a central concept of the object-oriented
programming paradigm.
 Unlike the other datatypes contained in the PHP language, an
object must be explicitly declared.
 This declaration of an object’s characteristics and behavior takes
place within something called a class.
OUTPUT
3 Special Datatypes:
Special datatypes include: resource and NULL.

(i) The special resource type is not an actual data type.


It is the storing of a reference to functions and resources
external to PHP.
A common example of using the resource data type is a
database call.
(ii). NULL:
 Null is a special data type which can have only one value:
NULL.
 A variable of data type NULL is a variable that has no value
assigned to it.
 If a variable is created without a value, it is automatically
assigned a value of NULL.
 Variables can also be emptied by setting the value to NULL:
OUTPUT
4. Scope and Lifetime of a PHP Variable:

………
OPERATORS :
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
. PHP language supports following type of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
 String Operators
 Increment/Decrement Operators
 BitWise Operators
Assignment Operators: The assignment operators assign a data value
to a variable. The simplest form of assignment operator just assigns
some value, while others (known as shortcut assignment operators)
perform some other operation before making the assignment.
String Operators:
PHP’s string operators provide a convenient way in which to
concatenate strings together.
There are two such operators,
including the concatenation operator (.) and
the concatenation assignment operator (.=).
Increment and Decrement Operators:
The increment (++) and decrement (--) operators present a
minor convenience in terms of code clarity, providing shortened
means by which you can add 1 to or subtract 1 from the current value
of a variable.
Bitwise Operators: Bitwise operators examine and manipulate
integer values on the level of individual bits that make up the integer
value.
Conditional Operator:
?:
Ternary. ($a == $b) ? 5 : 10

$a==$b is true, return 5. Otherwise 10


EXPRESSIONS
 An expression is a statement used to perform actions in a
program.
It consists of one or more operators with at least one operand.

Examples:
i) $a = 10; // This expression assigns integer value 10 to the variable $a
ii) $a = ―123‖; // This expression assigns string value ―123‖ to the variable $a
iii) $menu = ―PUSH‖; // This expression assigns ―PUSH‖ to the variable $menu
iv) $c=$a+$b; // This expression assigns sum of the value of $a and $b to the variable $c
v) $i++; // This expression post-increment the variable $a by 1.
STATEMENTS
Conditional / Selection Statements in PHP
: Conditional / Selection statements are used to perform different
actions based on different conditions.
In PHP we have the following conditional statements:

 if statement - executes some code only if a specified condition is true


 if...else statement - executes some code if a condition is true and another
code if the condition is false
 if...elseif....else statement - specifies a new condition to test, if the first
condition is false
 switch statement - selects one of many blocks of code to be executed
Loop Statements in PHP:
There is some situation to execute same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines
in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
 while - loops through a block of code as long as the specified
condition is true
 do...while - loops through a block of code once, and then repeats the
loop as long as the specified 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
 Break & Continue Statements- used to terminate the execution of
a loop prematurely & halt the current iteration of a loop but it does not
terminate the loop
(i). The if Statement:
It is one of the most commonplace constructs of any mainstream
programming language, offering a convenient means for conditional
code execution.
syntax:
if (expression)
{
statement
}
EXAMPLE:

OUTPUT
(ii) if…else statement:
If...else statement are a conditional statement which is use to
execute a statement when condition of valuable is true and
another statement will execute if valuable is false.
The if....else statement to execute some code if a condition is true
and another code if the condition is false.

Syntax: if (condition)
{ // code to be executed if condition is true; }
else { // code to be executed if condition is false; }
(iii) if...elseif....else statement:
If...elseif...else statement are a conditional statement which is use to select one
of several condition and execute the selected statement of condition.
The if....elseif...else statement to specify a new condition to test, if the first
condition is false.
Syntax:
if (condition)
{ // code to be executed if condition is true; }
else if(condition) { // code to be executed elseif condition is true; }
else { // code to be executed if condition is false; }
(iv) switch…case statement:
Switch statement are same with If...elseif...else statement, but
switch statement only use to comparing single variables with some
values is there. The switch statement is to select one of many blocks of
code to be executed.
Syntax: switch (n)
{
case label1: code to be executed if n=label1; break;
case label2: code to be executed if n=label2; break;
case label3: code to be executed if n=label3; break;
... …
default: code to be executed if n is different from all labels;
}
Looping Statements:
(i) while loop statement: The while statement will execute a block of
code if and as long as a test expression is true.
If the test expression is true then the code block will be executed.
After the code has executed the test expression will again be evaluated
and the loop will continue until the test expression is found to be false.
Syntax:
while (condition)
{
// code to be executed;
}
(ii)The do...while Statement:
 It is a variant of while but it verifies the loop conditional at the
conclusion of the block rather than at the beginning.
 syntax: do
{ statements }
while (expression);
 Both while and do...while are similar in function.
 The only real difference is that the code embedded within a while
statement possibly could never be executed, whereas the code
embedded within a do...while statement will always execute at
least once.
(iii).The for Statement:
The for statement offers a somewhat more complex looping
mechanism than does while.
syntax:

for (init counter; test counter; increment counter)


{ code to be executed for each iteration;
}
(iv) The foreach Statement:
The foreach loop - Loops through a block of code for each
element in an array.
The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.

syntax: foreach ($array as $value)


{
code to be executed;
}
PHP Break &Continue:
The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration
in the loop.
STRINGS:
A string is a sequence of characters treated as a contiguous group.
Strings are delimited by single or double quotes.
Example: "PHP is a great language"

PHP offers more than 100 functions collectively capable of


manipulating practically every imaginable aspect of a string.
strlen() function returns the length of a string
str_word_count() function counts the number of words in a
string.
strrev()-- function reverses a string.
OUTPUT
Comparing Two Strings:

compares two strings.


strcmp(string1,string2)

Return Value:
This function returns:0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2
strcasecmp() Function:

Compare two strings (case-insensitive):


Converting a String to All Lowercase:
The strtolower() function converts a string to all lowercase
letters, returning the modified string.
Nonalphabetical characters are not affected.
syntax: string strtolower(string str)
Example:
Converting a String to All Uppercase:
This is accomplished with the function strtoupper().
Its prototype follows: string strtoupper(string str)
Example:
Capitalizing the First Letter of a String:
The ucfirst() function capitalizes the first letter of the string str, if it is
alphabetical.
Its prototype follows: string ucfirst(string str)

Capitalizing Each Word in a String: The ucwords() function


capitalizes the first letter of each word in a string. Its prototype
follows: string ucwords(string str)
strrchr() Function: The strrchr() function finds the position of
the last occurrence of a string within another string, and returns all
characters from this position to the end of the string.

strstr() function searches for the first occurrence of a string


inside another string.
ARRAYS
 An array is a single variable that can hold more than one value at
once. You can think of an array as a list of values.
 Each value within an array is called an element, and each element is
referenced by its own index , which is unique to that array.
 To access an element's value whether you're creating, reading,
writing, or deleting the element you use that element's index.
 Any array can be created using array() method.
In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index


Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
The count() function is used to return the length (the number of
elements) of an array:

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Indexed Arrays:
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like
this:
(i) $cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:


(ii) $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Associative Arrays:
Associative arrays are arrays that use named keys that you assign to
them.
There are two ways to create an associative array:
(i) $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
(ii) $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Multidimensional arrays:
In Multi-dimensional array elements in the array can be an array, and
each element in the sub-array can be an array and so on.

Example:
Accessing an Array Element:
Accessing of array elements is the same as in other languages.
The brackets with the subscript of the key are used to access an
individual array element.
This is irrespective of the integer key or the string key.
Ex:
$score[‘sub1’] = 55;
$day[0] = “Sunday”;
Output:
print_r() function prints the information about a variable in a
more human-readable way.
Adding and Removing Array Elements:
i) Adding a value to the Front of an Array:
The array_unshift() function inserts new elements to an array. The
new array values will be inserted in the beginning of the array.
ii) Adding a value at the End of an Array:
The array_push() function inserts one or more elements to the end of
an array.
iii) Removing a value from the Front of an Array:
The array_shift() function removes the first element from an array, and
returns the value of the removed element.
iv) Removing a value at the End of an Array:
The array_pop() function deletes the last element of an array.
Locating / Searching Array Elements:
PHP introduces several functions that enable to search arrays in order to
locate array elements

i) Searching an Array: The function in_array() searches an array for a


specific value, returning TRUE if the value is found and FALSE
otherwise.
ii) Searching Associative Array Keys:
The function array_key_exists() returns TRUE if a specified key is
found in an array and FALSE otherwise
iii) Searching Associative Array Values:
The function array_search() searches an array for a specified value,
returning its key located and FALSE otherwise.
iv) Retrieving Array Keys: The function array_keys() returns an array
consisting of all keys located in an array. Its prototype as follows
v) Retrieving Array Values:
The function array_values() returns all values located in an array,
automatically providing numeric indexes for the returned array.
Its prototype as follows,
sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the
value
krsort() - sort associative arrays in descending order, according to the key
shuffle()- This function shuffles (randomizes the order of the elements in)
an array
merger()- It will merge multiple arrays
combine() - function creates an array by using the elements from one
"keys" array and one "values" array.
FUNCTIONS
The real power of PHP comes from its functions.
PHP has more than 1000 built-in functions, and in addition you can
create your own custom functions.
Prototype:
function function_name(args 1, args 2, …., args n )
{
// block of codes / statements;
}
• A function is a block of statements that can be used
repeatedly in a program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.
• A function may also return a value to the caller. The return statement is
included as the last statement, in a function, to return a value. The function
terminates if return statement is executed, or it has executed the last
statement in a function.
Example:
Parameter passing mechanisms are the methods of passing the
parameters, to a function.
The parameters that are passed in the call to a function are called, actual
parameters and the parameters that are listed in the function definition are
called, formal parameters.
Actual parameters can be any expression or a variable, but formal
parameters must be variables.
 An important point is that the number of actual parameters will be
unbound variables.
 On the other hand, if actual parameters are more, then the extra
parameters will be ignored.
 Thus, PHP supports functions with variable number of parameters.
 There are TWO parameter passing mechanisms.
 One is ‗Call by Value and
 second is ‗Call by Reference.
a) Call by Value:
 This is the default parameter passing mechanism of PHP.
 This mechanism copies the values of actual parameters, into the
formal parameters.
 If the called function changes the values of the formal parameters,
then there will be no change in the actual parameters because,
formal parameters are never copied back to the caller.
 Thus, call by value mechanism provides one-way communication
Default Argument Values:
Default values can be assigned to input arguments, which will be
automatically assigned to the argument if no other value is provided.
Recursive Functions: Recursive functions, or functions that call
themselves.
Introduction to Cookies
Cookies are text files stored on the client computer and they are kept
of use tracking purpose. PHP transparently supports HTTP cookies.
Cookies are usually set in an HTTP header.
Advantages of cookies:
a) To avoid entering repeated data at the client side.
b) It is useful to search the common data in search engines to increase
the searching speed
c) The business applications like e-commerce can use cookies
for performing financial and banking transactions.
Disadvantages:
a) Some unauthorized persons access client side resources.
b) Cookies are stored at client side machine.
PHP cookie is a small piece of information which is stored at client
browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser.
 Each time when client sends request to the server, cookie is
embedded with request.
Such way, cookie can be received at the server side.
Setting Cookies with PHP:
PHP provided setcookie() function to set a cookie.
This function requires upto six arguments and should be called before
tag.
For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:
1. Name - This sets the name of the cookie and is stored in an
environment variable called HTTP_COOKIE_VARS. This
variable is used while accessing cookies.
2. Value -This sets the value of the named variable and is the
content that you actually want to store.
3. Expiry - This specify a future time in seconds since 00:00:00
GMT on 1st Jan 1970. After this time cookie will become
inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
4. Path -This specifies the directories for which the cookie is valid. A
single forward slash character permits the cookie to be valid for all
directories.
5. Domain - This can be used to specify the domain name in very large
domains and must contain at least two periods to be valid. All cookies
are only valid for the host and domain which created them.
6. Security - This can be set to 1 to specify that the cookie should only
be sent by secure transmission using HTTPS otherwise set to 0 which
mean cookie can be sent by regular HTTP
Deleting Cookies :
Removing cookies is also a simple task.
 You should note that cookies will disappear by themselves if you
have set them up to doso.
Example : setcookie("cookie_user", $value, time()+3600);
/* expire in 1 hour */

 Cookies that have not been assigned a time to die will simply be
removed when the browser window closes.
Example: setcookie("cookie_user", $value);
 A user will want to be able to clear the cookies on a site. When
deleting a cookie you should assure that the expiration date is in the past,
to trigger the removal mechanism in your browser.
PHP predefined Mathematical functions:

: PHP has several predefined functions, for number values. Some of the most common
functions are,

abs — Absolute value


acos — Arc cosine
asin — Arc sine
atan — Arc tangent
base_convert — Convert a number between arbitrary
bases bindec — Binary to decimal
ceil — Round fractions up
decbin — Decimal to binary
dechex — Decimal to hexadecimal
decoct — Decimal to octal
deg2rad — Converts the number in degrees to the radian
exp — Calculates the exponent of e
floor — Round fractions down
fmod — floating point remainder (modulo) of the division
hexdec — Hexadecimal to decimal
log10 — Base-10 logarithm
log — Natural logarithm
max — Find highest value
min — Find lowest value
octdec — Octal to decimal
pi — Get value of pi
pow — Exponential expression
rand — Generate a random integer
round — Rounds a float
sin — Sine
sinh — Hyperbolic sine
sqrt — Square root
tan — Tangent
tanh — Hyperbolic tangent
Regular Expression:
 A regular expression is a sequence of characters that forms a
search pattern.
 When you search for data in a text, you can use this search pattern
to describe what you are searching for.
 A regular expression can be a single character, or a more
complicated pattern.
 Regular expressions can be used to perform all types of text
search and text replace operations.
In PHP, regular expressions are strings composed of delimiters, a
pattern and optional modifiers.
$exp = "/SREC/i";

In the example above, / is the delimiter, SREC is the pattern that is


being searched for, and i is a modifier that makes the search case-
insensitive
Regular Expression Functions:
PHP provides a variety of functions that allow you to use regular
expressions.
Commonly used functions
are: preg_match(), preg_match_all() and preg_replace()

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if
not
preg_match_all() Returns the number of times the pattern was found in
the string, which may also be 0
preg_replace() Returns a new string where matched patterns have
been replaced with another string
The preg_match() function will tell you whether a string contains matches
of a pattern.
The preg_match_all() function will tell you how many matches were
found for a pattern in a string.
The preg_replace() function will replace all of the matches of the pattern
in a string with another string.
Regular Expression Modifiers:
Modifiers can change how a search is performed.

Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for
the beginning or end of a string will match the
beginning or end of each line)
u Enables correct matching of UTF-8 encoded patterns
Regular Expression Patterns:
Brackets are used to find a range of characters:

Expression Description

[abc] Find one character from the options between the


brackets
[^abc] Find any character NOT between the brackets

[0-9] Find one character from the range 0 to 9


Metacharacters
Metacharacters are characters with a special meaning:

Metacharacter Description
| Find a match for any one of the patterns separated by | as
in: cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \
bWORD, or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal
number xxxx
Quantifiers
Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences
of n
n? Matches any string that contains zero or one occurrences
of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least
X n's
Example:
Using HTTP Headers:
 HTTP headers are powerful sets of functionality supported
by PHP.
 The most important aspect to remember about headers is
that they can be called only before any output has been
written to the web page.
 We can use them to control everything, including setting the
current page location, finding out what file format is being
displayed, and managing all aspects of the browser cache.
The header() function sends a raw HTTP header to a client.
It is important to notice that the header() function must be called
before any actual output is sent!
Syntax:
header(header, replace, http_response_code)
Parameter Description
header Required. Specifies the header string to send
replace Optional. Indicates whether the header should replace a
previous similar header or add a new header of the same
type. Default is TRUE (will replace). FALSE allows
multiple headers of the same type
http_respons Optional. Forces the HTTP response code to the
e_code specified value
header
The header string.
There are two special-case header calls. The first is a header that starts
with the string "HTTP/" (case is not significant), which will be used
to figure out the HTTP status code to send.
The second special case is the "Location:" header. Not only does it send
this header back to the browser, but it also returns a REDIRECT (302)
status code to the browser unless the 201 or a 3xx status code has already
been set.
USING SESSIONS

A session is a way to store information (in variables) to be used


across multiple pages.
Unlike a cookie, the information is not stored on the users
computer.
What is a PHP Session?
 When you work 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 or what you do, because the
HTTP address doesn't maintain state.
 Session variables solve this problem by storing user information to be
used across multiple pages (e.g. username, favorite color, etc). By
default, session variables last until the user closes the browser.
Start a PHP Session:

A session is started with the session_start() function.


Session variables are set with the PHP global variable: $_SESSION.
Destroying a PHP Session:
 A PHP session can be destroyed by session_destroy()
function.
 This function does not need any argument and a single call
can destroy all the session variables.
 If you want to destroy a single session variable then you
can use unset() function to unset a session variable.
User Authentication:
 PHP Login script, what will allow users to register, login and to log
out.
When somebody registers the username and the password is stored
in a MySQL table.
 When somebody tries to log in the script will verify if exists an user
with the given username and password in the MySQL table.
 If the login was successful a session is created and a welcome
message is displayed. From here the user can log out by destroying
the session.
Creating the users MySQL table:
 The username and the password of each user will be stored in a
MySQL table..
We need two columns: username and password.
we used the following file to create the table:
1. $_SERVER -- $HTTP_SERVER_VARS—
 Server and execution environment information Description
 $_SERVER is an array containing information such as headers,
paths, and script locations.
The entries in this array are created by the web server.
Working with Date and Time:
Dates are so much part of everyday life that it becomes easy to
work with them without thinking. PHP also provides powerful
tools for date arithmetic that make manipulating dates easy. The
PHP 5 date and time function library makes up a core part of the
language. The library is included by default, and no special
compilation or configuration directives are required to use these
functions: they are available in any working PHP installation.
These are built in functions in PHP and are used to do the following
operations.
a) To obtain current date and time.
b) For accounting for time zone.
c) For performing calculations on date and time
d) For converting between different date and times.
Getting the Time Stamp with time():
 The PHP date() function is used to format a time and/or date.
 PHP's time() function gives you all the information that you need about
the current date and time. It requires no arguments but returns an integer.
 The integer returned by time() represents the number of seconds elapsed
since midnight GMT on January 1, 1970.
 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: date(format, timestamp)
Parameter Description :
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current
date and time
PHP Date() - Format the Date The required format parameter in the
date() function specifies how to format the date/time.
Here are some characters that can be used:

 d - Represents the day of the month (01 to 31)


 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)

You might also like