PHP is one of the most popular programming languages for web development; the PHP
stands for Hypertext preprocessor or Personal Home Page. It is mainly used to development of
data-driven web applications. It is a server side scripting language
Evolution of PHP
In 1994 Ramus Leadorf first creates a set of CGI scripts to monitor page views for his
resume. This early version of PHP named as PHP/FI (Form Interpreter) it had supported for form
input and MySQL database
In 1997 Lerdof inproves PHP/FI 1.0 and released it as PHP/2.0 when the developers Andi
Gutmans and Zeev Suraski rewrote the PHP parse and released it as PHP3.0. it syntax are more
powerful and consistent
In 2000 PHP4.0 was released. It offered a new engine, better performance and reliability
and built in supported for sessions and object oriented features. In 2007 revealed that this version
of PHP, PHP4.x
PHP5.0 was released in 2004, was a radical redesign of PHP4.0 boasting a completely
rewritten engine, a much improved object model, and various security and performance. PHP 5.0
also introduced various new important tools such as common database access layer, Java-style
exception handling and integrated database engine
PHP 5.3 latest version of PHP was released in 2008. Some of the noticeable
improvements of this version are support for name spaces, a cleaner and more secure
environment for managing a variable space, built in support for SQLite 3 and a native driver for
MySQL.
Features of PHP
Performance: scripts are written in PHP execute faster than those written in other
scripting languages. The PHP5.0 engine was completely redesigned with an optimized memory
manager to improve performance, and is noticeably faster than previous version. In addition third
party accelerators are available to further improve performance
Portability: PHP is available for UNIX, Microsoft Windows, Mac OS and OS/2 and PHP
programs are portable between platforms. As a result a PHP application developed any OS and
we can run any other OS. This ability to easily undertake cross-platform development
Ease of Use: PHP is extremely sophisticated programming language. Its syntax is clear
and consistent, and it comes with perfect documentation for the 5000+ functions included with
the core distributions
Open source: PHP is an open-source project the language is developed by a worldwide
team of volunteers who make its source code is freely available on the web, and it may be used
without payment of licensing fees or investments in expensive hardware or software
Community support: PHP is the access it offers to creativity and imagination of hundreds
of developer across the world
Third-party Application support: one of the PHPs strength has historically been its
support for wide range of different databases including MySQL, PostgreSQL ORACLE and
MicrosoftSQL Server; PHP5.3 supports more than fifteen different database engineers
PHP developers can today read and write the GIF,JPEG and PNG image formats; send
and receive email using SMTP,IMAP and POP3 protocols; interface with web services using the
SOAP and REST protocol, validate input using Perl regular expression; create and manipulate
1
PDF documents. PHP can even access C libraries, Java classes and COM objects and take
advantages of program code written for these languages
Basic development concepts
When developing a PHP application for the web is to embedded PHP code into one or
more standard HTML documents using special tags
<html>
<head></head>
<body>
<div> <?php echo sqrt(49);?></div>
</body>
</html>
When such an HTML document is requested by user a PHP knows web server can recognize and
execute the PHP code blocks and interpolate the resulting output into the HTML document
before returning it to the requesting user
LAMP (Linux Operating System, the Apache HTTP Server) Development framework
1. A person opens his web browser at home and types in the URL to website. After looking
up the domain, his browser(client) sends an HTTP request to the corresponding server IP
address
2. The web server handling HTTP requests for the domain receives the request and notes
that the URL ends with a .php suffix. Because the server is programmed to automatically
redirect all such requests to the PHP layer, it simply invokes the PHP interpreter and
passes it the contents of the named file
3. The PHP interpreter parses the file, executing the code in the special PHP tags. Within
these tags, you can perform calculation, process user input, interact with a database read
and write files. Once script interpreter has completed executing the PHP instructions, it
returns the result to the browser cleans up after itself
4. The results returned by the interpreter are transmitted to client
A variable is simply a container thats used store numeric and non numeric information.
We can access this information through a name i.e variable name
PHP has some rules for naming variables
2
1. Every variable name must proceeded with a dollar ($) symbol.
2. Must begin with a letter or underscore character optionally followed by more letters,
numbers or underscore characters. Common punctuation marks such as commas,
quotation marks or periods are not permitted in the variable name
Ex $root, $r567, $query2 valid variable name
$5root , $t67%, $TY& invalid variable name
The equity (=) symbol is used to assign the value on the right side of the equation to
variable on the left
$name = Raghul Gandhi
Variable name assigned the value Raghul Gandhi
The echo statement is used to print the value of this variable to the webpage
You can also assign value to another variable
$firstname = Raghul
$name = $firstname // assign variable to another variable
$sum = $a + $b // perform calculation
echo $firstname is a first name of $name // Raghul is a first name of Raghul Gandhi
Destroying Variable
In PHP supports data types ranging from simple string and numeric types to more
complex arrays and objects
Data Types
3
Integer : it has support two types a) integer b) Floating point ( floats or double)
Integer are rounded number Floating point are decimal or fractional number.
Ex : $size = 15 // integer $temp = 98.32// floating point
String: This can hold letters, numbers and special characters. String value must be enclosed in
either single quotes or double quotes
Ex: $name = Abdul Kalam
NULL: Which is a special data types first introduced in PHP4 NULLs are used to represent
empty variable in PHP
Ex : $here = null // $here is NULL
PHP automatically determines a variables data type form the content it holds. And if the
variables content changes over the duration of a script, the language will automatically set the
variable to the appropriate new data type
<?php
$whoami = abirami
echo gettype (whoami) // output : String
$whoami = 99.8
echo gettype (whoami) // output : double
?>
As the script output demonstrates, the variable whoami begins with life as a string
assigned value abirami. It then assigned the number 99.8 which automatically converts it to a
floating-point variable. Following this, the variable is de-initialized with the unset() method.
Which removes its value and turns it into a NULL
PHP allows Type Casting, the name of the desired type is written in parentheses before
the variable which is to be cast
<?php
$foo = 10.23
$newfoo = (integer) $foo; // cast to integer
echo $newfoo //output is 10
?>
Function Purpose
is_bool() Test if a variable holds a Boolean value
is_numeric() Test if a variable holds a numeric value
is_int() Test if a variable holds an integer
is_float() Test if a variable holds a floating-point value
is_string() Test if a variable holds a string value
is_null() Test if a variable holds a NULL value
is_array() Test if a variable is an array
is_object() Test if a variable is an object
4
Using Constants
Constant value is doesnt change during execution of program. They are mostly used for
data that is known well in advance and that is used in multiple places within your application.
Constants are defined using PHPs define() function, which accepts two arguments: 1
name of the constant 2 . It value. Constant names must follow the same rules as variable name
with one exception: the $ prefix is not required for the constant name
Ex
<?php
define( pi, 3.17);
define( e, 2.718);
echo the value of pi is .pi and e is : .e// the value of pi is . 3.17 and e is : . 2.718
?>
Operator is a symbol that tells the PHP processor to perform certain action. It can be
classified based on their operation such as
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Other useful operator
Arithmetic operator
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Divide and return quotient
% Divide and return remainder
Ex
<?php
$a =10;
$b = 20;
$sum = $a+$b;
echo $a + $b = $sum\n; \\ addition of a and b
$diff = $a-$b;
echo $a - $b = $diff\n; \\ subtraction of a and b
$product = $a*$b;
5
echo $a + $b = $product \n; \\ product of a and b
$quotient = $a/$b;
echo $a / $b = $ quotient \n; \\ quotient of a and b
$remainder = $a % $b;
echo $a + $b = $remainder \n; \\ remainder of a and b
Relational operator
This type of operator used to compare one variable or value with another. It returns either
true or false according to the inputs
Operator Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type
Ex:
<? php
$a=15;
$b=17;
$c=17.3;
$d=17;
echo ($a > $b) //returns true
echo ($a < $b)// returns false
echo ($b >= $c); // returns true
echo ($b == $d); // return true
?>
Logic operators
The logic operators are necessary to combine one or more logical test. PHP has three
most commonly used logical operators such as follows
Operator Description
&& AND
|| OR
! NOT
Ex:
<?php
$price = 100;
$size = 18;
6
echo( $price > 50 && $size < 25); // return true when if both comparisons are true
echo( $price > 100 || $size < 10); // return true when if both comparisons are true
echo( ! $size > 10); // reverse of logical test
?>
Concatenating Strings
In PHP has addition-assignment operator, represented by the symbol += and some other
operator listed in the following table
Operator Description
+= Add and assign
-+ Subtract and assign
*= Multiply and assign
/= Divide and assign quotient
%= Divide and assign Remainder
.= Concatenation and assign (String only)
7
UNIT II
The PHP programmer evaluates different conditions in their program and takes decisions
based on whether conditions evaluate to true or false. These conditions, and the actions
associated with them, are expressed by means of programming construct called as conditional
statement.
if Statement
The statement of if is thus the condition to be evaluated, which is always enclosed in
parentheses. If the conditions evaluates to true, the code within the curly braces is executed; is it
evaluates to false, the code within curly braces is skipped.
Syntax of If Statement
if (conditional statement)
{
Block1
} //execute the above Block1 of statement if it is true else skips the Block1 Statement
Ex:
<?php
$number=98
if($number >0)
{
echo That number is positive; // print That number is positive
}
if-else statement
The improved version of if statement is if-else statement that allows you to define an
alternative set of actions that the program should take when the conditions specified evaluates to
false. Here we combine two actions into a single unified code block
8
Common Comparison Operators
Operator Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type
Ternary Operator
This operator represented by the question mark (?) symbol. Lets you represent an if else
conditional statement in a single
Syntax
Ex
<?php
$x =90;
echo ($x < 50 ) ? X is less than 50 : X is more than 50;
?>
if-elseif-else statement
The if else if-else statement lets you chain together multiple if-else statements. The if-
else if else statement executes different codes for more than two conditions
9
Syntax
if (condtion)
{
// code to be executed if this condition is true
}
else if (condition)
{
// code to be executed if this condition is true
}
else if (condition)
{
// code to be executed if this condition is true
}
else
{
// code to be executed when all conditions are false
}
Ex:
<?php
$today = Friday;
if ($today ==Monday)
{
echo Monday\s child is fair of face.;
}
else if ($today ==Tuesday)
{
echo Tuesday\s child is full of grace.;
}
else if ($today ==Wednesday)
{
echo Wednesday\s child is full of woe.;
}
else if ($today ==Thursday)
{
echo Thursday\s child has far to go.;
}
else if ($today ==Friday)
{
echo Friday \s child is loving and giving.;
}
else
{
echo Saturday \s child work hard for living.;
}
?>
10
The if-elseif-else construct as soon as the conditional statements evaluates to true, PHP
will execute the corresponding code, skip the remaining conditional tests, and jump straight to
the lines following the entire if-elseif-else block. Even if more than one conditional tests
evaluates to true, PHP will only execute the code corresponding to the first true test.
Switch-Case Statement
An alternative to the if-elseif-else statement is the switch-case statement, which does
almost the same thing. It tests a variable against a series of values until it finds a match, and then
executes the code corresponding to that match
The switch-case construct differs from the if-elseif-else construct in one important way.
Once PHP finds a case statement that evaluates true, it executes not only the code corresponding
to that case statement, but also the code for all subsequent case statements. If this is not you
want, add a break statement to end of each case statement. The default set of actions should take
if none of the other cases evaluate to true.
Syntax:
switch(n)
{
case label1:
code to be executed if n = label1;
break;
case label2:
code to be executed if n = label2;
break;
case label2:
code to be executed if n = label3;
break;
default:
code to be executes if n is different from all labels
Ex:
<?php
$favcolor = red;
switch($favcolor)
{
case red
echo your favorite color is red;
break;
case green
echo your favorite color is green;
break;
case blue
echo your favorite color is blue;
break;
11
case yellow
echo your favorite color is yellow;
break;
default:
echo Your favorite color is neither red, blue, green nor yellow;
}
?>
We will discuss about continue and break keywords used to control the loops execution.
12
Syntax
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop
<html>
<body>
<?php
$a = 0;
$b = 0;
</body>
</html>
13
Syntax
while (condition) {
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
</body>
14
</html>
Syntax
do {
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10
<html>
<body>
<?php
$i = 0;
$num = 0;
do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Loop stopped at i = 10
15
The for each loop statement
The for each statement is used to loop through arrays. For each pass the value of the
current array element is assigned to $value and the array pointer is moved by one and in the next
pass next element will be processed.
Syntax
foreach (array as value) {
code to be executed;
}
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
16
Example
In the following example condition test becomes true when the counter value reaches 3 and loop
terminates.
<html>
<body>
<?php
$i = 0;
</body>
</html>
Loop stopped at i = 3
17
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not
terminate the loop.Just like the break statement the continue statement is situated inside the
statement block containing the code that the loop executes, preceded by a conditional test. For
the pass encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes
true it just skip the code and next value is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
</body>
</html>
Value is 1
Value is 2
Value is 4
Value is 5
18
Working with String and Numeric Functions
PHP has over 75 built-in string manipulation functions, supporting operations ranging
from string repetition and reversal to comparison and search-and-replace
The str_repeat() function is accept two argument the string to be repeated and the no of
times to repeat
Ex
<?php
$str = hello ;
echo str_repeat($str,2); // output is hellohello
?>
Working with Substrings
PHP also allows you to slice a string into smaller parts with the substr() function. This
accepts three arguments, the original string, the position (offset) at which start slicing, and the
number of characters to return from the starting position
Ex
<?php
$str = Welcome to India ;
echo substr($str,3,4); // output is come
?>
19
Comparing, counting, and Replacing Strings
The strcmp() function performs a case-sensitive comparison of two strings, returning a
negative value if first is less than the second and a positive value if first is greater than the
second and zero if both are equal
Ex
<?php
$a = hello ;
$b = hello ;
$c = hEllo ;
echo strcmp($a,$b)); // output is 0
echo strcmp($a,$c)); // output is 1
?>
The str_word_count() is used to count no of word in a given string
Ex
<?php
$str = Welcome to PHP Programming ;
echo str_word_count($str); // output is 4
?>
The str_replace() function, designed specifically to perform find and replace operations.
This function accepts three arguments; the search term, the replacement term, and the string in
which to perform the replacement
Ex
<?php
$str = john@domain.net;
echo str_replace( @,at, $str); //john at domain.net
?>
Formatting Strings
PHPs trim() function can be used to remove leading and trailing whitespace from a
string. It useful when processing data entered into a web form
Ex
<?php
$str = ab c ;
echo trim($str); // output is ab c
?>
The strlower() and strupper() function are used to change the case of the string
Ex
<?php
$str = Welcome to PHP program;
echo strlower($str) // output is welcome to php program
?>
<?php
$str = Welcome to PHP program;
echo strupper($str) // output is WELCOME TO PHP PROGRAM
?>
20
You can also uppercase the first character of a string with the ucfirst() function
each first letter of word in a string is changes to uppercase with help of ucwords function
Ex
<?php
$str = welcome to PHP program;
echo ucfirst($str) // output is Welcome to php program
echo ucwords($str) // output is Welcome To PHP Program
?>
Working with HTML Strings
PHP also has some functions exclusively for working with HTML strings addslashes()
function which automatically escapes special characters in a string with backslashes
Ex
<?php
$str = Youre awake, arent you? ;
echo addslashes($str) // You \re awake, aren\t you?
?>
The stripslahes() function which removes all the backslashes from string
Ex
<?php
$str = John D\Souza says \ Catch you later.;
echo addslashes($str) // John D Souza says Catch you later.;
?>
The htmlentities() and htmlspecialchars() functions automatically convert special HTML
symbol (like < and >) into their corresponding HTML representations(< and &<hairline #>gt)
You can reverse the effect of htmlentities() and htmlspecialchars() function with the
html_entitiy_decode() and htmlspeicalchars_decode() functions.
<?php
$number=10;
echo ceil($number/3);
// output: 4
?>
21
<?php
$number = 10;
Echo floor($number/3); // output =3
?>
<?php
$number=-10;
echo abs($number/3);
// output: 3.3333333333333
?>
<?php
echo pow(4,3);
// 64
?>
<?php
echo log(100,10);
// 2
?>
In the above code, log function find the log of 100 which has base 10.
<?php
echo rand(1,100);
// Every time diffrent result
?>
<?php
echo bindec(1100);
// 12
?>
22
<?php
echo decbin(152);
// 10011000
?>
<?php
echo decoct(12);
// 14
?>
<?php
echo dechex(12);
// c
?>
11. hexdec(): This function helps to convert hexadecimal number to decimal number.
<?php
echo hexdec('b');
// 11
?>
12. octdec(): This function convert octal number into decimal number.
<?php
echo octdec(14);
// 12
?>
13. number_format(): This function helps to format a number with grouped thousands and
decimal.
<?php
echo number_format(1521254.0213);
// 1,521,254
?>
23
Unit III
24