0% found this document useful (0 votes)
7 views

PHP Mod 3 &4

The document provides an introduction to PHP fundamentals including: 1) PHP is a server-side scripting language used for building dynamic web applications. It allows embedding PHP code into HTML files. 2) Basic PHP syntax involves wrapping PHP code within <?php ?> tags. PHP files must have a .php extension. 3) Variables in PHP start with a $ sign followed by a case-sensitive name. The document discusses variable scope and types including local, global, static, and parameters.

Uploaded by

Alan augustin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PHP Mod 3 &4

The document provides an introduction to PHP fundamentals including: 1) PHP is a server-side scripting language used for building dynamic web applications. It allows embedding PHP code into HTML files. 2) Basic PHP syntax involves wrapping PHP code within <?php ?> tags. PHP files must have a .php extension. 3) Variables in PHP start with a $ sign followed by a case-sensitive name. The document discusses variable scope and types including local, global, static, and parameters.

Uploaded by

Alan augustin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

lOMoARcPSD|15218210

Php fundamentals- studying php language

PHP-Hypertext preprocessor (University of Calicut)

StuDocu is not sponsored or endorsed by any college or university


Downloaded by Sreelakshmi PH ([email protected])
lOMoARcPSD|15218210

PHP

a. INTRODUCTION TO PHP

• Getting started
PHP is a powerful tool for making dynamic and interactive Web pages.

PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

• PHP stands for PHP: Hypertext Preprocessor


• PHP is a server-side scripting language, like ASP
• PHP scripts are executed on the server
• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
• PHP is an open source software
• PHP is free to download and use

• Basic Syntax
A PHP script always starts with <?php and ends with ?>. A PHP script can be placed anywhere in
the document.

On servers with shorthand-support, you can start a PHP script with <? and end with ?>.

For maximum compatibility, we recommend that you use the standard form (<?php) rather than the
shorthand form.
<?php
?>
A PHP file must have a .php extension.

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP script that sends the text "Hello World" back to the
browser:
<html>
<body>

<?php
echo "Hello World";

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

?>

</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.

There are two basic statements to output text with PHP: echo and print.

• Advantages
PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP is FREE to download from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side

• Installing PHP on Linux-Setting apache-php.ini


Install PHP5 from http://www.php.net/manual/en/install.php

Download PHP
Download PHP for free here: http://www.php.net/downloads.php

Download MySQL Database


Download MySQL for free here: http://www.mysql.com/downloads/

Download Apache Server


Download Apache for free here: http://httpd.apache.org/download.cgi

b. VARIABLES & EXPRESSIONS

• Data types
As with algebra, PHP variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carName.

Rules for PHP variable names:

• Variables in PHP starts with a $ sign, followed by the name of the variable

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• The variable name must begin with a letter or the underscore character
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)
• A variable name should not contain spaces
• Variable names are case sensitive (y and Y are two different variables)
• Variable scope
The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has four different variable scopes:

• local
• global
• static
• parameter

Local Scope
A variable declared within a PHP function is local and can only be accessed within that function:

Example
<?php
$x=5; // global scope

function myTest()
{
echo $x; // local scope
}

myTest();
?>
The script above will not produce any output because the echo statement refers to the local scope
variable $x, which has not been assigned a value within this scope.

You can have local variables with the same name in different functions, because local variables are
only recognized by the function in which they are declared.

Local variables are deleted as soon as the function is completed.

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Global Scope
A variable that is defined outside of any function, has a global scope.

Global variables can be accessed from any part of the script, EXCEPT from within a function.

To access a global variable from within a function, use the global keyword:

Example
<?php
$x=5; // global scope
$y=10; // global scope

function myTest()
{
global $x,$y;
$y=$x+$y;
}

myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name
of the variable. This array is also accessible from within functions and can be used to update global
variables directly.

The example above can be rewritten like this:

Example
<?php
$x=5;
$y=10;

function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}

myTest();
echo $y;
?>

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you
want a local variable to not be deleted.

To do this, use the static keyword when you first declare the variable:

Example
<?php

function myTest()
{
static $x=0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

?>
Then, each time the function is called, that variable will still have the information it contained from
the last time the function was called.

Note: The variable is still local to the function.

Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code.

Parameters are declared in a parameter list as part of the function declaration:

Example
<?php

function myTest($x)
{
echo $x;
}

myTest(5);

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

?>

• Creating & assigning values to variables


PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to it:


$txt="Hello world!";
$x=5;
After the execution of the statements above, the variable txt will hold the value Hello world!, and
the variable x will hold the value 5.

Note: When you assign a text value to a variable, put quotes around the value.

• Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change
during the execution of the script (except for magic constants, which aren't actually constants). A
constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with
a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Example:-
<?php

// Valid constant names


define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");

// Invalid constant names


define("2FOO", "something");

// This is valid, but should be avoided:


// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).

• Comments in php
In PHP, we use // to make a one-line comment or /* and */ to make a comment block:

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

For example:-
<html>
<body>
<?php
//This is a comment

/*
This is
a comment
block
*/
?>
</body>
</html>

c. PHP OPERATORS

• Type of operators
The assignment operator = is used to assign values to variables in PHP.
The arithmetic operator + is used to add values together in PHP.

PHP Arithmetic Operators


Operator Name Description Example Result
x+y Addition Sum of x and y 2+2 4
x-y Subtraction Difference of x and y 5-2 3
x*y Multiplication Product of x and y 5*2 10
x/y Division Quotient of x and y 15 / 5 3
5%2 1
x%y Modulus Remainder of x divided by y 10 % 8 2
10 % 2 0
-x Negation Opposite of x -2
a.b Concatenation Concatenate two strings "Hi" . "Ha" HiHa

PHP Assignment Operators


The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of
the expression on the right. That is, the value of "$x = 5" is 5.
Assignment Same as... Description

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

x=y x=y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
a .= b a=a.b Concatenate two strings

PHP Incrementing/Decrementing Operators


Operator Name Description
++ x Pre-increment Increments x by one, then returns x
x ++ Post-increment Returns x, then increments x by one
-- x Pre-decrement Decrements x by one, then returns x
x -- Post-decrement Returns x, then decrements x by one

PHP Comparison Operators


Comparison operators allows you to compare two values:
Operator Name Description Example
x == y Equal True if x is equal to y 5==8 returns false
True if x is equal to y, and they are
x === y Identical 5==="5" returns false
of same type
x != y Not equal True if x is not equal to y 5!=8 returns true
x <> y Not equal True if x is not equal to y 5<>8 returns true
True if x is not equal to y, or they
x !== y Not identical 5!=="5" returns true
are not of same type
x>y Greater than True if x is greater than y 5>8 returns false
x<y Less than True if x is less than y 5<8 returns true
Greater than or
x >= y True if x is greater than or equal to y 5>=8 returns false
equal to
Less than or equal
x <= y True if x is less than or equal to y 5<=8 returns true
to

PHP Logical Operators


Operator Name Description Example
x=6
x and y And True if both x and y are true y=3
(x < 10 and y > 1) returns

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

true
x=6
True if either or both x and y are
x or y Or y=3
true
(x==6 or y==5) returns true
x=6
True if either x or y is true, but not
x xor y Xor y=3
both
(x==6 xor y==3) returns false
x=6
y=3
x && y And True if both x and y are true
(x < 10 && y > 1) returns
true
x=6
True if either or both x and y are
x || y Or y=3
true
(x==5 || y==5) returns false
x=6
!x Not True if x is not true y=3
!(x==y) returns true

PHP Array Operators


Operator Name Description
x+y Union Union of x and y
x == y Equality True if x and y have the same key/value pairs
True if x and y have the same key/value pairs in the same order
x === y Identity
and are of the same type
x != y Inequality True if x is not equal to y
x <> y Inequality True if x is not equal to y
x !== y Non-identity True if x is not identical to y

• Miscellaneous operators

PHP Miscellaneous Introduction


The misc. functions were only placed here because none of the other categories seemed to fit.

Installation
The misc functions are part of the PHP core. There is no installation needed to use these functions.

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Runtime Configuration
The behavior of the misc functions is affected by settings in the php.ini file.

Misc. configuration options:


Name Default Description Changeable
FALSE indicates that scripts will be
terminated as soon as they try to output
ignore_user_abort "0" PHP_INI_ALL
something after a client has aborted their
connection
Color for highlighting a string in PHP
highlight.string "#DD0000" PHP_INI_ALL
syntax
highlight.comment "#FF8000" Color for highlighting PHP comments PHP_INI_ALL
Color for syntax highlighting PHP
highlight.keyword "#007700" keywords (e.g. parenthesis and PHP_INI_ALL
semicolon)
highlight.bg "#FFFFFF" Color for background PHP_INI_ALL
highlight.default "#0000BB" Default color for PHP syntax PHP_INI_ALL
highlight.html "#000000" Color for HTML code PHP_INI_ALL
Name and location of browser-
browscap NULL PHP_INI_SYSTEM
capabilities file (e.g. browscap.ini)

PHP Misc. Functions


PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
connection_aborted() Checks whether the client has disconnected 3
connection_status() Returns the current connection status 3
connection_timeout() Deprecated in PHP 4.0.5 3
constant() Returns the value of a constant 4
define() Defines a constant 3
defined() Checks whether a constant exists 3
die() Prints a message and exits the current script 3
eval() Evaluates a string as PHP code 3
exit() Prints a message and exits the current script 3
get_browser() Returns the capabilities of the user's browser 3
highlight_file() Outputs a file with the PHP syntax highlighted 4

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

highlight_string() Outputs a string with the PHP syntax highlighted 4


ignore_user_abort() Sets whether a remote client can abort the running of a script 3
pack() Packs data into a binary string 3
php_check_syntax() Deprecated in PHP 5.0.5 5
Returns the source code of a file with PHP comments and
php_strip_whitespace() 5
whitespace removed
show_source() Alias of highlight_file() 4
sleep() Delays code execution for a number of seconds 3
time_nanosleep() Delays code execution for a number of seconds and nanoseconds 5
time_sleep_until() Delays code execution until a specified time 5
uniqid() Generates a unique ID 3
unpack() Unpacks data from a binary string 3
usleep() Delays code execution for a number of microseconds 3

PHP Misc. Constants


PHP: indicates the earliest version of PHP that supports the constant.
Constant Description PHP
CONNECTION_ABORTED
CONNECTION_NORMAL
CONNECTION_TIMEOUT
__COMPILER_HALT_OFFSET__ 5

d. CONDITIONAL TESTS AND EVENTS IN PHP

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• If …else
If
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time is less than 20:

Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
If….else
Use 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;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a
good night!" otherwise:

Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

else
{
echo "Have a good night!";
}
?>

• Switch
The switch statement is used to perform different actions based on different conditions.
Use the switch statement 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;
default:
code to be executed if n is different from both label1 and label2;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated
once. The value of the expression is then compared with the values for each case in the structure. If
there is a match, the block of code associated with that case is executed. Use break to prevent the
code from running into the next case automatically. The default statement is used if no match is
found.

Example
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

echo "Your favorite color is neither red, blue, or green!";


}
?>

e. FLOW CONTROL

• While
The while loop executes a block of code while a condition is true.
Syntax
while (condition)
{
code to be executed;
}
Example
The example below first sets a variable i to 1 ($i=1;).

Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1
each time the loop runs:
<html>
<body>

<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
?>

</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

• do while

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

The do...while statement will always execute the block of code once, it will then check the condition,
and repeat the loop while the condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The example below first sets a variable i to 1 ($i=1;).

Then, it starts the do...while loop. The loop will increment the variable i with 1, and then write some
output. Then the condition is checked (is i less than, or equal to 5), and the loop will continue to run
as long as i is less than, or equal to 5:
<html>
<body>

<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>

</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

• for
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
{

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

code to be executed;
}
Parameters:

• init: Mostly used to set a counter (but can be any code to be executed once at the beginning
of the loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at the end
of the iteration)
Note: The init and increment parameters above can be empty or have multiple expressions
(separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as the
variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs:
<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>

</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

• foreach

The foreach loop is used to loop through arrays.

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>

<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>

</body>
</html>
Output:
one
two
three

f. FUNCTIONS

• Structure
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:

• Give the function a name that reflects what the function does

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html>
<body>

<?php
function writeName()
{
echo "Kai Jim Refsnes";
}

echo "My name is ";


writeName();
?>

</body>
</html>
Output:
My name is Kai Jim Refsnes

• Arguments
To add more functionality to a function, we can add parameters. A parameter is just like a variable.

Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html>
<body>

<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br>";
}

echo "My name is ";


writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

writeName("Stale");
?>

</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<html>
<body>

<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br>";
}

echo "My name is ";


writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>

</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?

• Returning values
To let a function return a value, use the return statement.
Example
<html>
<body>

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}

echo "1 + 16 = " . add(1,16);


?>

</body>
</html>
Output:
1 + 16 = 17

• Recursion
A recursive function is a function that calls itself
Calculating factorials is a commonly cited example - the factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1, or
720, and is usually represented as 6! So, given that factorial 6 (6!) is 720, what is factorial 7, and
how does it relate to 6!? Well, clearly 7! is 7 * 6! - once you calculate 6!, it is simply a matter of
multiplying the result by 7 to get 7!
This equation can be represented like this: n! = n * ((n - 1)!) That is, the factorial for any given
number is equal to that number multiplied by the factorial of the number one lower - this is clearly a
case for recursive functions!
So, what we need is a function that will accept an integer, and, if that integer is not 0, will call the
function again, this time passing in the same number it accepted minus 1, then multiply that result by
itself. If it is sounding hard, then you are in for a surprise: the function to calculate factorials is made
up of only two lines of code. Here is a working script to calculate factorials:
<?php
function factorial($number) {
if ($number == 0) return 1;
return $number * factorial($number - 1);
}

print factorial(6);
?>
That will output 720, although you can easily edit the factorial() function call to pass in 20 rather
than 6, for example. Note that factorials increase in value very quickly (7! is 5040, 8! is 40320, etc),
and so you will eventually hit a processing limit - not time, but merely recursive complexity; PHP
will only allow you to have a certain level of recursion

• Built in functions

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

In PHP, there are more than 700 built-in functions.


Example:-
• Array functions
• Calendar functions
• Date functions
• Directory functions
• Error functions
• Filesystem functions
• Filter functions
• FTP functions
• HTTP functions
• LibXML functions
• Mail functions
• Math functions
• Misc functions
• MySQLi functions
• SimpleXML functions
• String functions
• XML Parser functions
• Zip functions

g. ARRAYS

• Array structure
An array stores multiple values in one single variable:

Example
<?php
$cars=array("Volvo","BMW","Toyota");

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could
look like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not
3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an
index number.
In PHP, the array() function is used to create an array:
array();

• Type of array
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Indexed arrays
There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):


$cars=array("Volvo","BMW","Toyota");
or the index can be assigned manually:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and then
prints a text containing the array values:

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:


$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The named keys can then be used in a script:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

• Multidimensional array
A multidimensional array is an array containing one or more arrays.

In a multidimensional 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.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?

• Array sorting
The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

Sort Functions For Arrays


• sort() - sort arrays in ascending order

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• 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

Sort Array in Ascending Order - sort()


The following example sorts the elements of the $cars array in ascending alphabetical order:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending numerical order:

Example
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>

Sort Array in Descending Order - rsort()


The following example sorts the elements of the $cars array in descending alphabetical order:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending numerical order:

Example
<?php
$numbers=array(4,6,2,22,11);
rsort($numbers);
?>

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Sort Array in Ascending Order, According to Value - asort()


The following example sorts an associative array in ascending order, according to the value:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
?>

Sort Array in Ascending Order, According to Key - ksort()


The following example sorts an associative array in ascending order, according to the key:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>

Sort Array in Descending Order, According to Value - arsort()


The following example sorts an associative array in descending order, according to the value:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
?>

Sort Array in Descending Order, According to Key - krsort()


The following example sorts an associative array in descending order, according to the key:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
krsort($age);
?>

h. OBJECT ORIENTED PROGRAMMING IN PHP

• Oops concept

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Object Oriented Programming (OOP) is a programming concept that treats functions and data as
objects

• Classes and Object


• Class: This is a programmer-defined datatype, which includes local functions as well as local
data. You can think of a class as a template for making many instances of the same kind (or class) of
object.

• Object: An individual instance of the data structure defined by a class. You define a class once
and then make many objects that belong to it. Objects are also known as instance.

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 line:

• The special form class, followed by the name of the class that you 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;

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP


Once you defined your class, then you can create as many objects as you 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;

• Accessing properties and methods


Class member variables are called “properties”.
• Advantages
OOP provides a clear modular structure for programs which makes it good for defining abstract
datatypes where implementation details are hidden and the unit has a clearly defined interface.
OOP makes it easy to maintain and modify existing code as new objects can be created with small
differences to existing ones.
OOP provides a good framework for code libraries where supplied software components can be
easily adapted and modified by the programmer. This is particularly useful for developing graphical
user interfaces.
• Constructors
Constructor Functions are special type of functions which are called automatically whenever an
object is created. So we take full advantage of this behaviour, by initializing many things through
constructor functions.

PHP provides a special function called __construct() to define a constructor. You can pass as many
as arguments you like into the constructor function.

Following example will create one constructor for Books class and it will initialize price and title for
the book at the time of object creation.

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

function __construct( $par1, $par2 ){


$this->price = $par1;
$this->title = $par2;
}

Now we don't need to call set function separately to set price and title. We can initialize these two
member variables at the time of object creation only. Check following example below:
$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 you can define a destructor function using function __destruct(). You
can release all the resourceses with-in a destructor.

• Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the extends
clause. The syntax is as follows:
class Child extends Parent {
<definition body>
}

The effect of inheritance is that the child class (or subclass or derived class) has the following
characteristics:
• Automatically has all the member variable declarations of the parent class.

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• Automatically has all the same member functions as the parent, which (by default) will work
the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
class Novel extends Books{
var publisher;
function setPublisher($par){
$this->publisher = $par;
}
function getPublisher(){
echo $this->publisher. "<br />";
}
}

Now apart from inherited functions, class Novel keeps two additional member functions.

i. COOKIES

• Setting
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.

• Accessing
The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it.
We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>

<html>
.....
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>

<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

Retrieve a Cookie Value


The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];

// A way to view all cookies


print_r($_COOKIE);
?>
In the following example we use the isset() function to find out if a cookie has been set:
<html>
<body>

<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
echo "Welcome guest!<br>";
?>

</body>
</html>

• Destroying
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

• Uses of cookie
To store username/password information so that the user doesn't have to log in every time they visit
the website ("remember me" sign ins).
To simply remember the user's name.
To keep track of a user's progress during a specified process.
To remember a user's theme.

• Limitations
Cookies aren't always enabled in all browsers
Cookie is hackable
j. SESSIONS

• session id
A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.
• predefined PHP session variables
When you are working with an application, you open it, do some changes and then you close it. This
is much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who you
are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later
use (i.e. username, shopping items, etc). However, session information is temporary and will be
deleted after the user has left the website. If you need a permanent storage you may want to store the
data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

<?php session_start(); ?>

<html>
<body>

</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.

Storing a Session Variable


The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>
Output:
Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

echo "Views=". $_SESSION['views'];


?>

Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:


<?php
session_start();
if(isset($_SESSION['views']))
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your stored session data.
• session and cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
A session variable is used to store information about, or change settings for a user session. Session
variables hold information about one single user, and are available to all pages in one application.
Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for
months if not years. Cookies, having their data stored on the client, work smoothly when you have a
cluster of web servers, whereas sessions are stored on the server, meaning in one of your web servers
handles the first request, the other web servers in your cluster will not have the stored information.
Sessions are stored on the server, which means clients do not have access to the information you
store about them - this is particularly important if you store shopping baskets or other information
you do not want you visitors to be able to edit by hand by hacking their cookies.
Session data, being stored on your server, does not need to be transmitted with each page; clients just
need to send an ID and the data is loaded from the local file. Finally, sessions can be any size you
want because they are held on your server, whereas many web browsers have a limit on how big
cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie
information.
k. FILE AND DIRECTORY ACCESS

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• read- write
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:
<html>
<body>

<?php
$file=fopen("welcome.txt","r");
?>

</body>
</html>
he following example generates a message if the fopen() function is unable to open the specified file:
<html>
<body>

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>

</body>
</html>

Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

Note: You cannot read from files opened in w, a, and x mode!


if (feof($file)) echo "End of file";

Reading a File Line by Line


The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?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);
?>

Reading a File Character by Character


The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

}
fclose($file);

• append files
If we want to add on to a file we need to open it up in append mode. The code below does just that.

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
PHP - File Write: Appending Data
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more
data.

PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
The only thing that is different is that the file pointer is placed at the end
of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:


Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

• file 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

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

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

• ownership and permissions


The chmod() function changes permissions of the specified file.

Returns TRUE on success and FALSE on failure.

Syntax
chmod(file,mode)

Parameter Description
file Required. Specifies the file to check
mode Required. Specifies the new permissions.
The mode parameter consists of four numbers:

• The first number is always zero


• The second number specifies permissions for the owner
• The third number specifies permissions for the owner's user group
• The fourth number specifies permissions for everybody else
Possible values (to set multiple permissions, add up the following numbers):

• 1 = execute permissions
• 2 = write permissions
• 4 = read permissions

Example
<?php
// Read and write for owner, nothing for everybody else
chmod("test.txt",0600);

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

// Read and write for owner, read for everybody else


chmod("test.txt",0644);

// Everything for owner, read and execute for everybody else


chmod("test.txt",0755);

// Everything for owner, read for owner's group


chmod("test.txt",0740);
?>
fileowner
The fileowner() function returns the user ID (owner) of the specified file.

This function returns the user ID on success or FALSE on failure.

Syntax
fileowner(filename)

Parameter Description
filename Required. Specifies the file to check

Example
<?php
echo fileowner("test.txt");
?>

• directory
The mkdir() function creates a directory.

This function returns TRUE on success, or FALSE on failure.

Syntax
mkdir(path,mode,recursive,context)

Parameter Description
path Required. Specifies the name of the directory to create
mode Optional. Specifies permissions. By default, the mode is 0777 (widest possible
access).
The mode parameter consists of four numbers:

• The first number is always zero

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• The second number specifies permissions for the owner


• The third number specifies permissions for the owner's user group
• The fourth number specifies permissions for everybody else
Possible values (to set multiple permissions, add up the following numbers):

• 1 = execute permissions
• 2 = write permissions
• 4 = read permissions
recursive Optional. Specifies if the recursive mode is set (added in PHP 5)
context Optional. Specifies the context of the file handle. Context is a set of options that
can modify the behavior of a stream (added in PHP 5)

Example
<?php
mkdir("testing");
?>

• uploading files

HTML Code:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
Here is a brief description of the important parts of the above code:

• enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function


properly.
• action="uploader.php" - The name of our PHP page that will be created, shortly.
• method="POST" - Informs the browser that we want to send information to the server
using POST.
• input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that
can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup
solution in PHP. We have set the max file size to 100KB in this example.

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.

PHP Code:
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
If the upload is successful, then you will see the text "The file filename has been uploaded". This is
because move_uploaded_file returns true if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error uploading the file, please try
again!" would be displayed.

l. STRING & REGULAR EXPRESSION

• string types
String variables are used for values that contain characters.

After we have created a string variable we can manipulate it. A string can be used directly in a
function or it can be stored in a variable.

In the example below, we create a string variable called txt, then we assign the text "Hello world!" to
it. Then we write the value of the txt variable to the output:

Example
<?php
$txt="Hello world!";
echo $txt;
?>

• string operators and functions

PHP 5 String Functions


The PHP string functions are part of the PHP core. No installation is required to use these functions.

Function Description

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

addcslashes() Returns a string with backslashes in front of the specified characters


addslashes() Returns a string with backslashes in front of predefined characters
bin2hex() Converts a string of ASCII characters to hexadecimal values
chop() Removes whitespace or other characters from the right end of a string
chr() Returns a character from a specified ASCII value
chunk_split() Splits a string into a series of smaller parts
convert_cyr_string() Converts a string from one Cyrillic character-set to another
convert_uudecode() Decodes a uuencoded string
convert_uuencode() Encodes a string using the uuencode algorithm
count_chars() Returns information about characters used in a string
crc32() Calculates a 32-bit CRC for a string
crypt() One-way string encryption (hashing)
echo() Outputs one or more strings
explode() Breaks a string into an array
fprintf() Writes a formatted string to a specified output stream
Returns the translation table used by htmlspecialchars() and
get_html_translation_table()
htmlentities()
hebrev() Converts Hebrew text to visual text
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
hex2bin() Converts a string of hexadecimal values to ASCII characters
html_entity_decode() Converts HTML entities to characters
htmlentities() Converts characters to HTML entities
htmlspecialchars_decode() Converts some predefined HTML entities to characters
htmlspecialchars() Converts some predefined characters to HTML entities
implode() Returns a string from the elements of an array
join() Alias of implode()
lcfirst() Converts the first character of a string to lowercase
levenshtein() Returns the Levenshtein distance between two strings
localeconv() Returns locale numeric and monetary formatting information
ltrim() Removes whitespace or other characters from the left side of a string
md5() Calculates the MD5 hash of a string
md5_file() Calculates the MD5 hash of a file
metaphone() Calculates the metaphone key of a string
money_format() Returns a string formatted as a currency string
nl_langinfo() Returns specific local information

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

nl2br() Inserts HTML line breaks in front of each newline in a string


number_format() Formats a number with grouped thousands
ord() Returns the ASCII value of the first character of a string
parse_str() Parses a query string into variables
print() Outputs one or more strings
printf() Outputs a formatted string
quoted_printable_decode() Converts a quoted-printable string to an 8-bit string
quoted_printable_encode() Converts an 8-bit string to a quoted printable string
quotemeta() Quotes meta characters
rtrim() Removes whitespace or other characters from the right side of a string
setlocale() Sets locale information
sha1() Calculates the SHA-1 hash of a string
sha1_file() Calculates the SHA-1 hash of a file
similar_text() Calculates the similarity between two strings
soundex() Calculates the soundex key of a string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_getcsv() Parses a CSV string into an array
str_ireplace() Replaces some characters in a string (case-insensitive)
str_pad() Pads a string to a new length
str_repeat() Repeats a string a specified number of times
str_replace() Replaces some characters in a string (case-sensitive)
str_rot13() Performs the ROT13 encoding on a string
str_shuffle() Randomly shuffles all characters in a string
str_split() Splits a string into an array
str_word_count() Count the number of words in a string
strcasecmp() Compares two strings (case-insensitive)
Finds the first occurrence of a string inside another string (alias of
strchr()
strstr())
strcmp() Compares two strings (case-sensitive)
strcoll() Compares two strings (locale based string comparison)
Returns the number of characters found in a string before any part of
strcspn()
some specified characters are found
strip_tags() Strips HTML and PHP tags from a string
stripcslashes() Unquotes a string quoted with addcslashes()
stripslashes() Unquotes a string quoted with addslashes()

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

Returns the position of the first occurrence of a string inside another


stripos()
string (case-insensitive)
Finds the first occurrence of a string inside another string (case-
stristr()
insensitive)
strlen() Returns the length of a string
Compares two strings using a "natural order" algorithm (case-
strnatcasecmp()
insensitive)
Compares two strings using a "natural order" algorithm (case-
strnatcmp()
sensitive)
strncasecmp() String comparison of the first n characters (case-insensitive)
strncmp() String comparison of the first n characters (case-sensitive)
strpbrk() Searches a string for any of a set of characters
Returns the position of the first occurrence of a string inside another
strpos()
string (case-sensitive)
strrchr() Finds the last occurrence of a string inside another string
strrev() Reverses a string
Finds the position of the last occurrence of a string inside another
strripos()
string (case-insensitive)
Finds the position of the last occurrence of a string inside another
strrpos()
string (case-sensitive)
Returns the number of characters found in a string that contains only
strspn()
characters from a specified charlist
Finds the first occurrence of a string inside another string (case-
strstr()
sensitive)
strtok() Splits a string into smaller strings
strtolower() Converts a string to lowercase letters
strtoupper() Converts a string to uppercase letters
strtr() Translates certain characters in a string
substr() Returns a part of a string
Compares two strings from a specified start position (binary safe and
substr_compare()
optionally case-sensitive)
substr_count() Counts the number of times a substring occurs in a string
substr_replace() Replaces a part of a string with another string
trim() Removes whitespace or other characters from both sides of a string
ucfirst() Converts the first character of a string to uppercase
ucwords() Converts the first character of each word in a string to uppercase
vfprintf() Writes a formatted string to a specified output stream
vprintf() Outputs a formatted string

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

vsprintf() Writes a formatted string to a variable


wordwrap() Wraps a string to a given number of characters

• regular expression & functions

ereg_replace — Replace regular expression


Example:-
<?php

$string = "This is a test";


echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?>
ereg — Regular expression match
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";
}
?>
eregi_replace — Replace regular expression case insensitive
Example:-
<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>
eregi — Case insensitive regular expression match
Example:-
<?php
$string = 'XYZ';
if (eregi('z', $string)) {
echo "'$string' contains a 'z' or 'Z'!";
}
?>
split — Split string into array by regular expression
<?php
// Delimiters may be slash, dot, or hyphen

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>
spliti — Split string into array by regular expression case insensitive
<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>
The above example will output:
Array
(
[0] =>
[1] => BBB
[2] => CCC
[3] => DDD
[4] => EEEaGGGA
)
sql_regcase — Make regular expression for case insensitive match
<?php
echo sql_regcase("Foo - bar.");
?>
The above example will output:
[Ff][Oo][Oo] - [Bb][Aa][Rr].

m. DATE & TIME

• Date time format


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

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

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)
<?php
echo date("Y/m/d") . "<br>";
echo date("Y.m.d") . "<br>";
echo date("Y-m-d");
?>
The output of the code above could be something like this:
2009/05/11
2009.05.11
2009-05-11

• Validating a date

checkdate — Validate a Gregorian date


Example:-
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
The above example will output:
bool(true)
bool(false)

PHP 5 Date/Time Functions


Function Description
checkdate() Validates a Gregorian date
Adds days, months, years, hours, minutes, and seconds to a
date_add()
date
Returns a new DateTime object formatted according to a
date_create_from_format()
specified format

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

date_create() Returns a new DateTime object


date_date_set() Sets a new date
date_default_timezone_get() Returns the default timezone used by all date/time functions
date_default_timezone_set() Sets the default timezone used by all date/time functions
date_diff() Returns the difference between two dates
date_format() Returns a date formatted according to a specified format
date_get_last_errors() Returns the warnings/errors found in a date string
date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of the string
date_interval_format() Formats the interval
date_isodate_set() Sets the ISO date
date_modify() Modifies the timestamp
date_offset_get() Returns the timezone offset
Returns an associative array with detailed info about a
date_parse_from_format()
specified date, according to a specified format
Returns an associative array with detailed info about a
date_parse()
specified date
Subtracts days, months, years, hours, minutes, and seconds
date_sub()
from a date
Returns an array containing info about sunset/sunrise and
date_sun_info()
twilight begin/end, for a specified day and location
date_sunrise() Returns the sunrise time for a specified day and location
date_sunset() Returns the sunset time for a specified day and location
date_time_set() Sets the time
date_timestamp_get() Returns the Unix timestamp
date_timestamp_set() Sets the date and time based on a Unix timestamp
date_timezone_get() Returns the time zone of the given DateTime object
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local date and time
Returns date/time information of a timestamp or the current
getdate()
local date/time
gettimeofday() Returns the current time
gmdate() Formats a GMT/UTC date and time
gmmktime() Returns the Unix timestamp for a GMT date
Formats a GMT/UTC date and time according to locale
gmstrftime()
settings
idate() Formats a local time/date as integer
localtime() Returns the local time

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

microtime() Returns the current Unix timestamp with microseconds


mktime() Returns the Unix timestamp for a date
strftime() Formats a local time and/or date according to locale settings
strptime() Parses a time/date generated with strftime()
strtotime() Parses an English textual datetime into a Unix timestamp
time() Returns the current time as a Unix timestamp
Returns an associative array containing dst, offset, and the
timezone_abbreviations_list()
timezone name
timezone_identifiers_list() Returns an indexed array with all timezone identifiers
timezone_location_get() Returns location information for a specified timezone
timezone_name_from_ abbr() Returns the timezone name from abbreviation
timezone_name_get() Returns the name of the timezone
timezone_offset_get() Returns the timezone offset from GMT
timezone_open() Creates new DateTimeZone object
timezone_transitions_get() Returns all transitions for the timezone
timezone_version_get() Returns the version of the timezone db

n. PHP DEBUGGING

• error handling and debugging

PHP Error and Logging Functions


PHP: indicates the earliest version of PHP that supports the function.
Function Description PHP
debug_backtrace() Generates a backtrace 4
debug_print_backtrace() Prints a backtrace 5
error_get_last() Gets the last error occurred 5
Sends an error to the server error-log, to a file or to a
error_log() 4
remote destination
error_reporting() Specifies which errors are reported 4
restore_error_handler() Restores the previous error handler 4
restore_exception_handler() Restores the previous exception handler 5
set_error_handler() Sets a user-defined function to handle errors 4
set_exception_handler() Sets a user-defined function to handle exceptions 5
trigger_error() Creates a user-defined error message 4
user_error() Alias of trigger_error() 4

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

• customized errors
PHP Exception Handling
Exceptions are used to change the normal flow of a script if a specified error occurs.

What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.

Exception handling is used to change the normal flow of the code execution if a specified error
(exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:

• The current code state is saved


• The code execution will switch to a predefined (custom) exception handler function
• Depending on the situation, the handler may then resume the execution from the saved code
state, terminate the script execution or continue the script from a different location in the
code
We will show different error handling methods:

• Basic use of Exceptions


• Creating a custom exception handler
• Multiple exceptions
• Re-throwing an exception
• Setting a top level exception handler
Note: Exceptions should only be used with error conditions, and should not be used to jump to
another place in the code at a specified point.

Basic Use of Exceptions


When an exception is thrown, the code following it will not be executed, and PHP will try to find the
matching "catch" block.

If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Lets try to throw an exception without catching it:

Downloaded by Sreelakshmi PH ([email protected])


lOMoARcPSD|15218210

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>
The code above will get an error like this:
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Downloaded by Sreelakshmi PH ([email protected])

You might also like