Anda di halaman 1dari 36

OPEN SOURCE SOFTWARE UNIT - IV IV I.

T

1 DEPARTMENT OF INFORMATION TECHNOLOGY

Introduction to PHP
PHP, or PHP: Hypertext Preprocessor, is a cross-platform server side scripting
language that is primarily used to create dynamic and interactive web pages, which means that
it can be used on almost every major operating system. It can be embedded into HTML and is
generally run on web servers that are running the Apache HTTP server software. It is free
software and is free to download and use.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is an open source, server side scripting language that is embedded in HTML.
It is used to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
PHP is compatible with all the major web servers like Apache, Microsoft IIS.
It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and CORBA),
making n-tier development a possibility for the first time.
PHP Syntax is very similar to C and Perl languages.
Common uses of PHP
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from forms, save data into database.
We can add, delete, and modify elements within our database through PHP.
Through PHP, we can access cookies variables and can set cookies.
Using PHP, we can restrict users to access some pages of our website.
It can encrypt data.

Characteristics of PHP
Five important characteristics make PHP's practical nature possible:
Simplicity
Efficiency
Security
Flexibility
Familiarity

Familiarity
Programmers from many backgrounds will already be familiarized with the PHP
language. Many of the languages constructs are borrowed from C and Perl, and in many cases
PHP code is almost indistinguishable from the typical C program.

Simplicity
There is no need to include libraries, special compilation directives, or anything. The
PHP engine simply begins executing the code after the first escape sequence (<?php). If the
code is syntactically correct, it will be executed exactly as it is displayed.




OPEN SOURCE SOFTWARE UNIT - IV IV I.T

2 DEPARTMENT OF INFORMATION TECHNOLOGY

Efficiency
Efficiency is an extremely important consideration for working in a multiuser
environment such as the WWW. PHP 4.0 introduced resource allocation mechanisms and more
support for object-oriented programming, in addition to session management features.

Security
PHP provides developers and administrators with a flexible and efficient set of security
safeguards. These safeguards can be divided into two frames of reference: system level and
application level.

Flexibility
Because PHP is an embedded language, it is extremely flexible towards meeting the
needs of the developer. Although PHP is generally used in conjunction with HTML, it can also
be integrated with the languages like JavaScript, WML, XML, and many others. Browser
dependency is not an issue because PHP scripts are compiled entirely on the server side before
being sent to the user.
Server side Processing with PHP
Generally, PHP works in partnership with a web server, which enables us to build
interactive and dynamic web pages. A web server is the software that delivers web pages to
our website's users. The PHP software works in conjunction with the web server to allow the
functionality necessary to deliver the interactive and dynamic web pages.
When a website user goes to a web page with a .php extension, for example by typing
the URL into the web browser directly or by clicking a link, the request is sent to a web server.
That request is then sent to the PHP interpreter.
The PHP interpreter also communicates with file systems, databases and email servers
as needed, and then delivers the request to the web server to return to the web browser.
In comparison, when a website user goes to a purely HTML generated web page; the
server sends HTML data to the web browser without having the code interpreted.

1. The user enters a web page address in the browsers location bar.
2. The browser breaks apart that address and sends the name of the page to the
host. For example, http://www.phone.com/login.php requests the page
login.php from www.phone.com.
3. The web server process on the host receives the request for login.php.
4. The web server reads the login.php file from the hosts hard drive.
5. The web server detects that the PHP file isnt just a plain HTML file, so it asks
another processthe PHP interpreterto process the file.
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

3 DEPARTMENT OF INFORMATION TECHNOLOGY

6. The PHP interpreter executes the PHP code that it finds in the text it received
from the web server process. Included in that code are calls to the MySQL
database.
7. PHP asks the MySQL database process to execute the database calls.
8. The MySQL database process returns the results of the database query.
9. The PHP interpreter completes execution of the PHP code with the data from
the database and returns the results to the web server process.
10. The web server returns the results in the form of HTML text to the browser.
11. The web browser uses the returned HTML text to build the web page on users
screen.

PHP Environment
In order to develop and run PHP Web pages, three vital components need to be installed on
our computer system.
Web Server - PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely
available Apache Server.
Database - PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database.
PHP Parser - In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser.

PHP Syntax
The syntax for PHP scripting blocks start with a <?php delimiter and end with a ?>
delimiter. A PHP scripting block can be placed anywhere within an HTML document. If PHP
is included within an HTML document, the document must have a .php extension.
<?php
// PHP scripting block
?>
There are other PHP delimiters that can be used, however, it is recommended that you
use the standard form <?php and ?> delimiters for maximum compatibility.
Other PHP delimiters that we can use are
Shorthand delimiters (<? ?>).
ASP style delimiters (<% %>)
Placing our code inside <script> tags with the language attribute set to php.
The examples below show us how each style of PHP delimiter looks.
On servers that have shorthand support enabled, we can use the scripting block
delimiters <? and ?>.

Syntax:
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

4 DEPARTMENT OF INFORMATION TECHNOLOGY

<?
// PHP code
?>
We can use the ASP style delimiters <% and %> by turning on the asp_tags directive.
Syntax:
<%
// PHP code
%>
We can also place PHP code within the <script> and </script> tags with the language
attribute set to php
Syntax
<script language="php">
// PHP code
</script>
Each PHP statement must end with a semi-colon (;). This tells the PHP interpreter that
that PHP statement has ended. If a semi-colon is not included at the end of the line of code, the
interpreter will assume that the PHP statement continues onto the next line.
The PHP interpreter condenses all sequential whitespace in PHP scripts to a single
whitespace. This allows programmers to structure their code into a more readable format.
PHP comment tags
PHP allows us to add comments that are visible to us, the programmer, to PHP code
without the PHP interpreter trying to execute the comments as code. The PHP comments tags
are // for single-line comments and enclosing /* and */ tags for multiple-line comments.
<?php
// this is a single-line comment
?>
<?php
/*
this is a multiple-line comment
this is a multiple-line comment
*/
?>









OPEN SOURCE SOFTWARE UNIT - IV IV I.T

5 DEPARTMENT OF INFORMATION TECHNOLOGY

Running PHP Scripts
To run the PHP scripts in XAMPP, we need to follow the steps like
Step 1:
Start XAMPP Control Panel Application and start Apache and MySQL services.

Step 2:
1. To run PHP code or PHP script we need a .php file. So create a file with a name called
"myFirstPHPScript.php". For example
<?php
echo "Hello World! This is my first PHP code snippet!!"; ?>
2. Save this file in htdocs folder available in the XAMPP installation directory i.e
c:\xampp. Every PHP file or PHP Project must be stored in this htdocs directory. If it a
big project then keeps all the PHP, HTML, CSS, JavaScript files in one folder and
place them in the htdocs directory.

Step 3:
Open any web browser(Chrome, IE, Firefox, Safari, Opera etc.) . Simply type
http://localhost/myFirstPHPScript.php in the address bar. Then we get the page like


PHP Variables
Variables are used for storing values, such as numbers, strings or function results, so
that they can be used many times in a script. Once a variable is declared, it can be used over
and over again throughout your script.




OPEN SOURCE SOFTWARE UNIT - IV IV I.T

6 DEPARTMENT OF INFORMATION TECHNOLOGY

Declaration of Variables in PHP
To declare a variable in PHP, first type the dollar sign symbol ($), followed by the
name of the variable. The name of the variable is followed by the assignment operator (=),
which is followed by the value that WE want to assign to the variable, followed by the semi-
colon (;).

Variable Naming Conventional and Rules

A variable name must start with a letter or an underscore "_"
A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9,
_ )
A variable name should not contain spaces. If a variable name should be more than one
word, it should be separated with underscore ($my_string), or with capitalization
($myString)
The variable names are case-sensitive, so $myvar is different from $myVar.

The syntax of PHP variables is
<?php
$variable_name = value;
?>
Variable Types
PHP has a total of eight data types which we use to construct our variables. Out of eight
data types, four are scalar types, two are compound types and other two are special types.
Scalar Data types:
Integers: are whole numbers, without a decimal point, like 4195.
Doubles: are floating-point numbers, like 3.14159 or 49.1.
Booleans: have only two possible values either true or false.
Strings: are sequences of characters, like 'PHP supports string operations.
Compound Types
Arrays : are the variables to hold the multiple values
Objects: are instances of programmer-defined classes, which can packed up both the
values and functions that are specific to the class.
Special Types
NULL: is a special type that only has one value: NULL.
Resources: are special variables that hold references to resources external to PHP such
as database connections.



OPEN SOURCE SOFTWARE UNIT - IV IV I.T

7 DEPARTMENT OF INFORMATION TECHNOLOGY

Integers
They are whole numbers, without a decimal point, like 4195 represented in both
positive and negative. Integers can be assigned to variables, or they can be used in expressions,
like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals
have a leading 0X.
For most common platforms, the largest integer is 2,147,483,647, and the smallest
integer is -2,147,483,647.

Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of
decimal places needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5
Boolean
They have only two possible values either TRUE or FALSE.
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");

Strings
They are sequences of characters, like "PHP supports string operations". Following are
valid examples of string.
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally); ?>
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

8 DEPARTMENT OF INFORMATION TECHNOLOGY

This will produce following result:
My $variable will not print!\n
My name will print
NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL
value, simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case
insensitive; you could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.
Arrays
In PHP an array can have numeric key, associative key or both. The value of an array
can be of any type. To create an array use the array() language construct like this.

<?php
$numbers = array(1, 2, 3, 4, 5, 6);
$age = array("mom" => 45, "pop" => 50, "bro" => 25);
$mixed = array("hello" => "World", 2 => "It's two";
echo "numbers[4] = {$numbers[4]} <br>";
echo "My mom's age is {$age['mom']} <br>";
echo "mixed['hello'] = {$mixed['hello']} <br>";
echo "mixed[2] = {$mixed[2'}";
?>

Scope of the Variables
Every variable that is defined in a PHP script within an area of accessibility called a
scope. The scope of that variable determines which elements in that script can access that
variable.
PHP variables can be one of four scope types:
Local variables
Global variables
Super Global Variables





OPEN SOURCE SOFTWARE UNIT - IV IV I.T

9 DEPARTMENT OF INFORMATION TECHNOLOGY

Local Variables
Variables that are defined in the body of a function are local for the function. Local
variables are not accessible in the global scope.
Global Variables
Variables that are defined in the main body of a script are global variables. Global variables
are not accessible in the local scope.
To show the difference between local and global variables, the below PHP code
demonstrated
<?php
$globalVar = 1;
function localFunc() {
echo "The value in localFunc is: $globalVar.<br />";
}
function globalFunc() {
global $globalVar;
echo "The value in globalFunc is: $globalVar";
}

localFunc();
globalFunc();
?>
The PHP code above outputs:
The value in localFunc is:The value in globalFunc is: 1

Super Global Variables
Super global variables are built-in arrays that have a global scope. Super global arrays
are available anywhere in the program, including in functions.
Array Description
$_POST Contains all of the variables that are submitted in a form using the POST
method.
$_GET Contains all of the variables that are submitted in a form using the GET
method.
$_COOKIE Contains all of the cookie variables.
$_REQUEST Contains all of the variables that are in the $_POST, $_GET and $_COOKIE.
$_FILES Contains the names of files that have been uploaded.
$_SERVER Contains information about your server.
$_ENV Contains information that is provided by your operating system.
$GLOBALS Contains all of the global variables.




OPEN SOURCE SOFTWARE UNIT - IV IV I.T

10 DEPARTMENT OF INFORMATION TECHNOLOGY

PHP Constants
A PHP constant is a variable that cannot be changed after the initial value is assigned
during the execution of the script. We can create a constant variable using the define ()
function. The function accepts 2 arguments.
Syntax:
define (<constant name>, <value>);
The first must be a string and represents the name which will be used to access the
constant. A constant name is case-sensitive by default and by convention, is always
uppercase. A valid constant name starts with a letter or underscore, followed by any
combination of letters, numbers or underscores. Constant names must be in quotes
when they are defined.
The second argument is the value of the constant and can be a string or numbers and
can be set explicitly.
The scope of a constant is global, which means that we can access constants anywhere in
our script without regard to scope.
<?php
define ("WEBSITE", "WebDevelopmentTutorials.com");
define(PI,3.17);
echo WEBSITE;
EchoPI value is:.PI;?>

PHP Operators
In PHP, operators are used to manipulate or perform operations on values and expressions.
Operators allow us to assign values to variables, perform arithmetic operations, concatenate
strings, compare values and perform Boolean operations.
PHP Assignment Operators
PHP Arithmetic Operators
PHP String Concatenation Operator
PHP Increment and Decrement Operators
PHP Logical Operators
PHP Comparison Operators
PHP Arithmetic Operators
PHP arithmetic operators are used to perform various arithmetic operations. They are

Operator Description Example
+ Adds two operands A + B will give
30
- Subtracts second operand from the first A - B will give -
10
* Multiply both operands A * B will give
200
/ Divide numerator by denominator B / A will give 2
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

11 DEPARTMENT OF INFORMATION TECHNOLOGY

% Modulus Operator and remainder of after
an integer division
B % A will give
0
++ Increment operator, increases integer value
by one
A++ will give 11
-- Decrement operator, decreases integer
value by one
A-- will give 9
PHP Assignment Operators
The assignment operator (= or equals), is used to assign a value to a variable or to
assign a variable to another variable's value. The assignment operator can also be used in
combination with other mathematical operators to change the value of a variable.

Operator Description Example
= Simple assignment operator,
Assigns values from right side
operands to left side operand
C = A + B will assign value of A +
B into C
+= Add AND assignment operator, It
adds right operand to the left
operand and assign the result to
left operand
C += A is equivalent to C = C + A
-= Subtract AND assignment
operator, It subtracts right
operand from the left operand and
assign the result to left operand
C -= A is equivalent to C = C - A
*= Multiply AND assignment
operator, It multiplies right
operand with the left operand and
assign the result to left operand
C *= A is equivalent to C = C * A
/= Divide AND assignment operator,
It divides left operand with the
right operand and assign the result
to left operand
C /= A is equivalent to C = C / A
%= Modulus AND assignment
operator, It takes modulus using
two operands and assign the result
to left operand
C %= A is equivalent to C = C %
A

PHP String Concatenation Operator
The PHP concatenation operator (.) is used to combine 2 sting values to create one
string. The concatenation operator us useful when WE are combining strings with values from
constants and arrays.
<?php
$variable1="Hello";
$variable2="World";
echo $variable1 . " " . $variable2;
?>
The code above outputs:
Hello World








OPEN SOURCE SOFTWARE UNIT - IV IV I.T

12 DEPARTMENT OF INFORMATION TECHNOLOGY

PHP Increment and Decrement Operators
PHP increment and decrement operators are used to increment and decrement numeric
values.
++$value(pre-increment) operator
The PHP ++$value(pre-increment) operator adds 1 to a value before the value is used
in the expression in which it is contained.
<?php
$value = 1;
echo ++$value;
?>
The code above outputs:
2
$value++(post-increment) operator
The PHP $value++(post-increment) operator adds 1 to a value after the value is used in
the expression in which it is contained.
<?php
$value = 1;
echo $value++;
echo "<br />";
echo $value;
?>
The code above outputs:
1
2
--$value(pre-decrement) operator
The PHP --$value(pre-decrement) operator subtracts 1 from a value before the value is
used in the expression in which it is contained.
<?php
$value = 2;
echo --$value;
?>
The code above outputs:
1
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

13 DEPARTMENT OF INFORMATION TECHNOLOGY

$value--(post-drecrement) operator
The PHP $value--(post-drecrement) operator subtracts 1 from a value after the value is
used in the expression in which it is contained.
<?php
$value = 2;
echo $value--;
echo "<br />;
echo $value;
?>
The code above outputs:
2
1
PHP Logical Operators
PHP logical operators are used to perform Boolean operations to compare one value to another
to determine if a statement is true or false.

Operator Description Example
and Called Logical AND operator. If both
the operands are true then then
condition becomes true.
(A and B) is
true.
or Called Logical OR Operator. If any of
the two operands are non zero then
then condition becomes true.
(A or B) is
true.
&& Called Logical AND operator. If both
the operands are non zero then then
condition becomes true.
(A && B) is
true.
|| Called Logical OR Operator. If any of
the two operands are non zero then
then condition becomes true.
(A || B) is true.
! Called Logical NOT Operator. Use to
reverses the logical state of its
operand. If a condition is true then
Logical NOT operator will make false.
!(A && B) is
false.
PHP Comparison Operators
PHP comparison operators compare values and return Boolean true or false values
depending on the result.

Operator Description Example
== Checks if the values of two operands are equal or not, if yes
then condition becomes true.
(A == B) is not
true.
!= Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(A != B) is true.
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

14 DEPARTMENT OF INFORMATION TECHNOLOGY

> Checks if the value of left operand is greater than the value of
right operand, if yes then condition becomes true.
(A > B) is not
true.
< Checks if the value of left operand is less than the value of
right operand, if yes then condition becomes true.
(A < B) is true.
>= Checks if the value of left operand is greater than or equal to
the value of right operand, if yes then condition becomes
true.
(A >= B) is not
true.
<= Checks if the value of left operand is less than or equal to the
value of right operand, if yes then condition becomes true.
(A <= B) is true.


Conditional Statements
Conditional statements allow us to specify blocks of code which will be executed only if
certain conditions are met. PHP supports following four decision making statements:
If statement: It allows one to execute select lines of code only when specified
conditions are true.
if...else statement - use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of
several condition are true
switch statement If we wish to test a single expression against a number of values,
the switch statement is used.

if Statement
The if statement is one of the most important features of every programming language.
It allows one to execute lines of code only when specified conditions are true.
Syntax
if (condition)
code to be executed if condition is true;



For Example
<?php
$number = 5;
if ($number < 10)
echo "5 is less than 10.";
?>
The code above outputs:
5 is less than 10.
If there will be more than one statement following the if condition, we will need to
enclose the statements in brackets ({}). For single statements, the use of the brackets is
optional.
<?php
$number = 5;
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

15 DEPARTMENT OF INFORMATION TECHNOLOGY

if ($number < 10)
{
echo "5 is less than 10.<br />";
echo "5 is my lucky number.<br />";
echo "It is also my favorite number.";
}
?>
The code above outputs:
5 is less than 10.
5 is my lucky number.
It is also my lucky number.
if-else Statement
If the tested condition returns false, PHP allows us to specify another block of code to
be executed using the else keyword. Each of these conditionally executed blocks of code is
known as a branch, and each branch must be placed within braces if it contains more than one
line of code.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

<?php
$number = 5;
if ($number < 10)
{
echo "5 is less than 10";
}
else
{
echo "5 is less than 10 is not true";
}
?>
The code above outputs:
5 is less than 10

elseif statement
PHP provides the elseif keyword to test alternative conditions if the condition in the if
portion of the statement is not true. Any number of elseif statements may be used with an if
statement. The final else branch then allows us to specify code that should be executed if none
of the if or elseif conditions is true.
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

16 DEPARTMENT OF INFORMATION TECHNOLOGY

Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
For example
<?php
$number = 10;
if ($number < 10)
{
echo "the variable \$number is less than 10";
}
elseif ($number == 10)
{
echo "the variable \$number is equal to 10";
}
else
{
echo "the variable \$number is less than 10 is not true";
}
?>
The code above outputs: the variable $number is equal to 10
Switch Statement
A PHP switch statement allows us to set up a list of conditions with a block of
statements for each condition. The switch statement tests the value of one variable and
executes the block of statements for the matching variable, or cases.

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

}
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

17 DEPARTMENT OF INFORMATION TECHNOLOGY

For Example
<?php
$state = "TX";
switch($state){
case "CA";
echo "I live in California";
break;
case "NY";
echo "I live in New York";
break;
case "TX";
echo "I live in Texas.";
break;
}
?>

Iterative Statements
Loops are a means of executing a block code a given number of times, or until a certain
condition is met.
There are a number of different loop statements in PHP:
While loop : PHP while loops will execute a block of code if and as long as a specified
condition is true.
do...while loop : PHP do while loops execute a block of code at least once and then it will
repeat the loop as long as a condition is true.
for loop : PHP for loops execute a block of code a specified number of times.
foreach loop : PHP foreach are used to loop through arrays.
The while loop
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;
}

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

18 DEPARTMENT OF INFORMATION TECHNOLOGY

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;

while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 1 and num = 40

do...while Loop
do ... while statements are similar to while statements, except that the condition is
tested at the end of each iteration, rather than at the beginning. This means that the loop will
always execute at least once
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 );
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

19 DEPARTMENT OF INFORMATION TECHNOLOGY

echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10


For statement
The for statement is used when we know how many times you want to execute a
statement or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}

The for statement takes three expressions inside its parentheses, separated by semi-
colons. The first is an assignment statement to initialize the loop control variable. This
statement is executed only once, before the first iteration of the loop. The second is a Boolean
expression that is evaluated at the beginning of each iteration. If this expression evaluates to
true, the iteration proceeds. If false, the loop terminates. The third is a statement which
executes at the end of each iteration of the loop. It is usually used to increment or decrement
the loop control variable.
Example
<html>
<body>
<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

20 DEPARTMENT OF INFORMATION TECHNOLOGY

foreach loop statement
The foreach 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);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
PHP Arrays
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100 variables it
is easy to define an array of 100 length.
There are three different kinds of arrays and each array value is accessed using an ID which is
called array index.

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

21 DEPARTMENT OF INFORMATION TECHNOLOGY

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 represented by
numbers. By default array index starts from zero.
Creating Numeric Array
We can create numeric array in two different ways.
Direct assignment
The simplest way to create an array is to assign a value into the specific index of the
array, like this

$my_array[1] = The first thing in my array that I just made;

If $my_array was an unbound variable before this statement, it will now be a variable bound
to an array with one element. If instead $my_array was already an array, the string will be
stored in association with the integer key 1.
If no value was associated with that number before, a new array slot will be created to hold it.
If a value was associated with 1, the previous value will be overwritten

The array() construct
The other way to create an array is via the array() construct, which creates a new array
from the specification of its elements. In its simplest version, array() is called with no
arguments, which creates a new empty array. In its next simplest version, array() takes a
comma separated list of elements to be stored. The result is that the elements are stored in the
array in the order specified and are assigned integer keys beginning with zero.
For example, the statement:

$fruit_basket = array(apple, orange, banana, pear);

causes the variable $fruit_basket to be assigned to an array with four string elements (apple,
banana, orange, pear), with the indices 0, 1, 2, and 3, respectively.

For example
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

22 DEPARTMENT OF INFORMATION TECHNOLOGY

$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
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.

Specifying indices using array()
The array() constructs offers us a special syntax for specifying key/value pairs
separated by commas, where the key and value are separated by the special symbol =>.

Consider the following statement:

$fruit_basket = array(red => apple, orange => orange, yellow => banana, green =>
pear);
Example
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

23 DEPARTMENT OF INFORMATION TECHNOLOGY


echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Retrieving Values from Arrays
Retrieving by index
The most direct way to retrieve a value is to use its index. If we have stored a value in
$my_array at index 5, $my_array[5] should evaluate to the stored value. If $my_array has
never been assigned, or if nothing has been stored in it with an index of 5, $my_array[5] will
behave like an unbound variable.

The list() construct
The list() is used to assign several array elements to variables in succession. Suppose
that the following two statements are executed:

$fruit_basket = array(apple, orange, banana);
list($red_fruit, $orange_fruit) = $fruit_basket;

This will assign the string apple to the variable $red_fruit and the string orange to
the variable $orange_fruit with no assignment of banana, because we didnt supply enough
variables. The variables in list() will be assigned to elements of the array in the order they were
originally stored in the array.

Using Iteration functions
To support the iteration through the array elements, internally the array elements are
stored sequentially and associated with these sequential elements, there are two memory
structures like
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

24 DEPARTMENT OF INFORMATION TECHNOLOGY






foreach structure
This is the simplest way of retrieving the array elements iteratively. The syntax for
foreach is

foreach ($array_variable as $value_variable) {
// .. do something with the value in $value_variable
}

If the array is having key/value pair elements, then the syntax for foreach statement is

foreach ($array_variable as $key_var => $value_var) {
// .. do something with $key_var and/or $value_var
}

Iterating with current() and next()
The current() function returns the stored value that the current pointer points to.
When an array is newly created with elements, the element pointed to will always be the first
element. The next() function first advances that pointer and then returns the current value
pointed to. If the next() function is called when the current pointer is already pointing to the
last stored value then the function returns a false value.

$fruit_basket = array(apple, orange, banana);
$current_item = current($fruit_basket);
if ($current_item)
print($current_item<BR>);
else
print(Theres nothing to print);
while($current_item = next($fruit_basket))
print($current_item<BR>);

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

25 DEPARTMENT OF INFORMATION TECHNOLOGY

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.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

26 DEPARTMENT OF INFORMATION TECHNOLOGY

String Functions in PHP

substr() : This function returns the part of the string as an output.
Syntax:
substr(<string>,<start>,[<length>]);

Explanation:
String: It is mandatory parameter. The string from which the part is to be extracted
is mentioned here.
Start: The start in the string from which the characters are to be extracted

Positive number - Start at a specified position in the string
Negative number - Start at a specified position from the end of the string
0 - Start at the first character in string

Length: It is an optional parameter. It specifies the length of the string which is to be
extracted.

o Positive number - The length to be returned from the start parameter
o Negative number - The length to be returned from the end of the string

Example 1:
<?php echo substr("Hello world",6); ?> //Returns world

Example 2 :
<?php echo substr("Hello world",6,4); ?> // Returns worl

strlen() : This function returns the length of the string

Syntax:
strlen(<string>);

Explanation:
String : It is mandatory field. The string whose length is to be found out is mentioned
here.

Example 1:
<?php echo strlen("Hello world"); ?> // Returns 11

trim() : This function removes the whitespaces from both start and the end of the string.

Syntax :
trim(<string>);

Explanation :
String : It is mandatory field. The string of which the whitespaces are to be
removed is passed as parameter.

Example 1:
<?php echo trim( " Hello World "); ?> // returns Hello World. If we go view source
then we can see that there are no whitespaces.

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

27 DEPARTMENT OF INFORMATION TECHNOLOGY

strtolower() : This function converts the string to lower case

Syntax :
strtolower(<string>);

Explanation :
String : It is mandatory field. The string which is to be converted to lower case is passed
here.

Example 1:
<?php echo strtolower("HELLO WORLD"); ?> // Returns hello world


strtoupper() : This function converts the string to upper case

Syntax :
strtoupper(<string>);

Explanation :
String : It is mandatory field. The string which is to be converted to upper case is passed
here.

Example 1:
<?php echo strtoupper("hello world"); ?> // Returns HELLO WORLD

strcmp() : The strcmp() function compares two strings. This function returns:

0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2

Syntax :
strcmp(<string1>,<string2>);

Explanation :
String1 : It is mandatory. The first string comes here.
String 2 : It is mandatory. The Second string comes here.

Example 1: <?php echo strcmp("Hello world!","Hello world!"); ?> //Returns 0

PHP Regular Expressions
Regular expressions are nothing more than a sequence or pattern of characters. They
provide the foundation for pattern-matching functionality.
Using regular expression we can search a particular string inside another string, we can
replace one string by another string and we can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression.

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

28 DEPARTMENT OF INFORMATION TECHNOLOGY

POSIX Regular Expressions
PERL Style Regular Expressions
POSIX Style Regular Expression
POSIX-style regular expressions are ultimately descended from the regex pattern-
matching techniques used in Unix command-line shells. The following the rules for
constructing regular expression.

Characters that are not special are matched literally. The letter a in a pattern, for
example, matches the same letter in a target string.
The special character ^ matches the beginning of a string only, and the special
character $ matches the end of a string only.
The special character . matches any character.
The special character * matches zero or more instances of the previous regular
expression, and + matches one or more instances of the previous expression.
A set of characters enclosed in square brackets matches any of those characters the
pattern [ab] matches either a or b. You can also specify a range of characters in
brackets by using a hyphen the pattern [a-c] matches a, b, or c.
Special characters that are escaped with a backslash (\) lose their special meaning and
are matched literally.

Some of the examples for PHP regular expressions

Expression Description
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p's.
p?
It matches any string containing zero or more p's. This is just an alternative
way to use p*.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
PHP currently offers some functions for searching strings using POSIX-style regular
expressions:



OPEN SOURCE SOFTWARE UNIT - IV IV I.T

29 DEPARTMENT OF INFORMATION TECHNOLOGY

Function Description
ereg()
The ereg() function searches a string specified by string for a string
specified by pattern, returning true if the pattern is found, and false
otherwise.
Syntax: int ereg ( string $pattern , string $string , array &$regs )
eregi()
The eregi() function searches throughout a string specified by pattern for a
string specified by string. The search is not case sensitive.
split()
The split() function will divide a string into various elements, the
boundaries of each element based on the occurrence of pattern in string.

Example

<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
echo "$regs[3].$regs[2].$regs[1]";
} else {
echo "Invalid date format: $date";
}
?>

PHP Functions
PHP function is a piece of code which takes one or more input values in the form of
parameter and does some processing and returns a value.
There are two parts for the functions
Creating a PHP Function
Calling a PHP Function
Creating PHP Function
It is very easy to create our own PHP function. While creating a function, its name
should start with keyword function and all the PHP code should be put inside {and } braces as
shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

30 DEPARTMENT OF INFORMATION TECHNOLOGY

<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
You are really a nice person, Have a nice time!
PHP Functions with Parameters
PHP allows us to pass the parameters inside a function. We can pass as many as
parameters our like. These parameters work like variables inside the function. Following
example takes two integer parameters and adds them together and then prints them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is : 30
PHP Functions with returning value
A function can return a value using the return statement in conjunction with a value or
object. The return stops the execution of the function and sends the value back to the calling
code.
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

31 DEPARTMENT OF INFORMATION TECHNOLOGY

For example
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>
This will display following result:
Returned value from the function : 30
Setting Default Values for Function Parameters
We can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints Hello in case of no value passed.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = Hello)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result:
This is test
Hello
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

32 DEPARTMENT OF INFORMATION TECHNOLOGY



PHP and OOP
PHP supports the concepts of Object oriented programming by classes and objects. It
has the facility to implement inheritance, polymorphism, data abstraction and encapsulation.

Defining PHP Classes
The general form for defining a new class in PHP is as follows:
<?php
class phpClass{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
Here is the description of each element:
The special form class, followed by the name of the class that we want to define.
A set of braces enclosing any number of variable declarations and function definitions.
Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a constant
value.
Function definitions look much like standalone PHP functions but are local to the class
and will be used to set and access object data.
Example:
Here is an example which defines a class of Books type:
<?php
class Books{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $var;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

33 DEPARTMENT OF INFORMATION TECHNOLOGY

}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
Creating Objects in PHP
Once we defined the class, then we can create as many objects as we like of that class
type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Calling Member Functions
After creating the objects, we will be able to call member functions related to that
object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling
member functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now we call another member functions to get the values set by in above example:
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce following result:
Physics for High School
Advanced Chemistry
Algebra
10
15
7
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

34 DEPARTMENT OF INFORMATION TECHNOLOGY

Constructor Functions
Constructor Functions are special type of functions which are called automatically
whenever an object is created. PHP provides a special function called __construct() to define
a constructor. We can pass as many as arguments we like into the constructor function.
For example
function __construct( $par1, $par2 ){
$this->price = $par1;
$this->title = $par2;
}
Now we don't need to call this function separately to set price and title. We can
initialize these two member variables at the time of object creation only. For example
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce following result:
Physics for High School
Advanced Chemistry
Algebra
10
15
7
Destructor
Like a constructor function we can define a destructor function using function
__destruct(). All the resources can be released with-in a destructor.
PHP File Handling
File Handling or processing in PHP is not different than any other language. There are 3
steps for using the data in a file.
1. Open the file. If the file doesnt already exist create it or catch the error gracefully.
2. Write/Read data from the file.
3. Close the file.

OPEN SOURCE SOFTWARE UNIT - IV IV I.T

35 DEPARTMENT OF INFORMATION TECHNOLOGY

Opening a File
The fopen() function is used to open files in PHP. The first parameter of this function
contains the name of the file to be opened and the second parameter specifies in which mode
the file should be opened. If the fopen() function is unable to open the specified file, it returns
0 (false).
The file may be opened in one of the following modes:
Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn't
exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't
exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't
exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

Example
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
Closing a File
The fclose() function is used to close an open file. For example
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
OPEN SOURCE SOFTWARE UNIT - IV IV I.T

36 DEPARTMENT OF INFORMATION TECHNOLOGY

Reading data from a file
We can read the data from a file line by line by using fgets() function. We cal also read
the data as a single character from a file by using fgetc( ) function.
For example
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file); ?>
?>
Writing data into a file
We can write to a file by using fwrite() function PHP. For this we have to open the file
in write mode and if write permission is there then only we can open it in write mode.
For example
<?
$body_content="This is my content"; // Store some text to enter inside the file
$file_name="test_file.txt"; // file name
$fp = fopen ($file_name, "w");
// Open the file in write mode, if file does not exist then it will be created.
fwrite ($fp,$body_content); // entering data to the file
fclose ($fp); // closing the file pointer
?>

Anda mungkin juga menyukai