Sunteți pe pagina 1din 121

PHP

CS3001
Lecture 13 / Slide 2

Introduction to PHP
 Server side technology for dynamic webpage generation,
command line scripting and client-GUI applications
 Scripting language
 Code is directly inserted in HTML documents
 Hypertext Pre-processor
 PHP code is executed by server and client receives
processed results as an HTML document
 Compatibility of different browsers problem is solved
 Script is never visible to client
 Page extension is .php

CS3001
Lecture 13 / Slide 3

example1.php
Actual Source File
<HTML>
<BODY>
<?
echo ("<H1>This is an example</H1>");
?>
</BODY>
</HTML>
Client Side Source
<HTML>
<BODY>
<H1>This is an example</H1>
</BODY>
</HTML>

CS3001
Lecture 13 / Slide 4

How to run PHP pages


 Web Server & PHP Engine required
 PHP engine is present on web server to process PHP
code and generate web pages as output.
 Web Server Apache ( www.apache.org )
 PHP Engine www.php.net

CS3001
Lecture 13 / Slide 5

Executing PHP pages


 Command line execution:
$ chmod +x simple.php
$ ./simple.php
(or)
$ php simple.php

 Browser:- Type url


http://localhost/index.php

CS3001
Lecture 13 / Slide 6

helloworld.php
<HTML>
<BODY>
<?
echo ("<H1>Hello World!</H1>");
?>
</BODY>
</HTML>

- Page present under standard directory


- URL: http://localhost/helloworld.php
- URL: http://web.iiit.ac.in/~<username>/helloworld.php

CS3001
Lecture 13 / Slide 7

Comments Single & Multi Line

<?php
echo "Hello World!"; // prints Hello World!
echo "<br />Psst...You can't see my PHP
comments!"; // echo "nothing";
# echo Single Line";
// echo single line";
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>
Output:
Hello World!
Psst...You can't see my PHP comments!

CS3001
Lecture 13 / Slide 8

Variables
 Names are preceded by $ symbol
 Variables must start with a letter or underscore "_
followed by any number of alphabets, digits or
underscores.
 Variables should not include spaces or other special or
reserved characters to define the names of a variable
 Case-sensitive


$var1 and $VAR1 are different variables

CS3001
Lecture 13 / Slide 9

Variables - Example


<HTML>
<BODY>
<?
$website = "http://www.bitafterbit.com";
echo ("<BR>Surf to: $website");
echo ('<BR>Surf to: $website');
?>
</BODY>
</HTML>

 Double quotes are used for interpolation while single quotes


does not interpolate

CS3001
Lecture 13 / Slide 10

Heredoc

 Create multi-line strings without using quotations


<?
$my_string = <<<TEST
Tizag.com
Webmaster Tutorials
Unlock your potential!
TEST;
echo $my_string;
?>

Command prompt Output:


Tizag.com
Webmaster Tutorials
Unlock your potential!

<?
echo <<<END
This uses the "here document"
syntax to output multiple lines
with $variable interpolation. Note
that the here document terminator
must appear on a line with just a
semicolon no extra whitespace!
END;
?>

 The closing sequence TEST; must occur on a line by itself and


cannot be indented!
 It will not span multiple lines on browser because we didnt
have any <br /> tags contained inside our string! !

CS3001
Lecture 13 / Slide 11

String Concatenation operator


 The period "." is used to add two strings together
<?
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";
?>

Output:
Hello Billy!

CS3001
Lecture 13 / Slide 12

Arithmetic Operators
<?
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiply = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo Subtraction: 6 - 2 = ".$subtraction.\n";
echo Multiplication: 5 * 3 = ".$multiply.\n";
?>
Output:
Subtraction: 6 - 2 = 4
Multiplication: 5 * 3 = 15

CS3001
Lecture 13 / Slide 13

Comparison Operators
Comparison
Operator
==

Description
Checks if 1st value is equal to 2nd value

>

Checks if 1st value is greater than 2nd value

<

Checks if 1st value is lesser than 2nd value

!=

Checks if 1st value is not equal to 2nd value

>=

Checks if 1st value is greater than or equal to 2nd value

<=

Checks if 1st value is lesser than or equal to 2nd value

CS3001
Lecture 13 / Slide 14

Arithmetic & Assignment Operators


Op

Example

Equivalent Operation

+=

$x += 2;

$x = $x + 2;

-=

$x -= 4;

$x = $x - 4;

*=

$x *= 3;

$x = $x * 3;

/=

$x /= 2;

$x = $x / 2;

%=

$x %= 5;

$x = $x % 5;

.=

$my_str.="hello";

$my_str = $my_str . "hello";

CS3001
Lecture 13 / Slide 15

Pre/Post-Increment & Pre/Post-Decrement


<?
$x =
echo
echo
echo
echo
$x =
echo
echo
echo
echo
?>

4;
$x++. ;
$x. ;
$x--. ;
$x.\n;
4;
++$x. ;
$x. ;
--$x. ;
$x. ;

Output:
4 5 5 4
5 5 4 4

CS3001
Lecture 13 / Slide 16

Logical Operators
Logical Operator
&&

Description
Boolean AND

||

Boolean OR

Boolean XOR

Boolean NOT

CS3001
Lecture 13 / Slide 17

If statement
<?
$a=3; $b=2;
if ($a > $b)
print "a is bigger than b";
?>
Output:
a is bigger than b

CS3001
Lecture 13 / Slide 18

If-else statement
<?
$Lastname = "Bit";
if ($Lastname == "Bit")
echo ("Hello, Mr. Bit!");
else
echo ("Who are you?");
?>
Output:
Hello, Mr. Bit!

CS3001
Lecture 13 / Slide 19

HTML & PHP


<HTML>
<BODY>
<?

$surname = "Bit";
if ($surname == "Bit"):
?>
Hello, Mr. Bit!
<?
else:
?>
Who are you?
<?
endif
?>
</BODY>
</HTML>

Output:
Hello, Mr. Bit!

<?
if (condition) :
?>
HTML instructions
<? endif ?>

CS3001
Lecture 13 / Slide 20

elseif
<?
$a=3; $b=3;
if ($a > $b) {
print "a is bigger than b";
}
elseif ($a == $b) {
print "a is equal to b";
}
else {
print "a is smaller than b";
}
?>
Output:
a is equal to b

CS3001
Lecture 13 / Slide 21

Switch vs If - Else
<?
$var=2;
switch ($var) {
case 1:
echo ("\$var is 1");
break;
case 2:
echo ("\$var is 2");
break;
case 5:
echo ("\$var is 5");
break;
default:
echo ("\$var value isnt
1, 2 or 5, but $var");
break;
}
Use escape character
?>

<?
$var=2;
if ($var==1)
echo ("\$var value is 1");
elseif ($var==2)
echo ("\$var value is 2");
elseif ($var==1)
echo ("\$var value is 3");
else
echo("\$var value isn't 1, 2,
or 5, but $var");
?>

here to print $

CS3001
Lecture 13 / Slide 22

For loop & break, continue

for (expr1; expr2; expr3) statement


<?
for($i=1; $i<=10; $i++)
{
print $i ;
}
?>
Output:
1 2 3 4 5 6 7 8 9 10

<?
for ($i=1;;$i++)
{
if ($i > 10)
break;
if ($i==4)
continue;
print $i ;
}
?>
Output:
1 2 3 5 6 7 8 9 10

CS3001
Lecture 13 / Slide 23

For Loop HTML table creation


<HTML>
<BODY>
<?
echo ("<TABLE ALIGN=CENTER BORDER=1 CELLSPACING=1
CELLPADDING=5>");
for ($j=1;$j<=5;$j++)
{
echo ("<TR>");
for ($k=1;$k<=3;$k++)
echo ("<TD> Line $j, Cell $k </TD>");
echo("</TR>");
}
echo ("</TABLE>");
?>
</BODY>
</HTML>

CS3001
Lecture 13 / Slide 24

While Loop (1)


<?
$i = 1;
while ($i <= 10)
{
print $i++;
}
?>
Output:
12345678910

CS3001
Lecture 13 / Slide 25

While Loop (2)


<HTML>
<BODY>
<?
$j=1;
echo ("<TABLE ALIGN=CENTER BORDER=1 CELLSPACING=1 CELLPADDING=5>");
while ($j<=5)
{
echo ("<TR>");
$k=1;
while ($k<=3)
{
echo ("<TD> Line $j, Cell $k </TD>");
$k++;
}
echo("</TR>");
$j++;
}
echo ("</TABLE>");
?>
</BODY>
</HTML>

CS3001
Lecture 13 / Slide 26

While Loop - Alternative


<?
while (condition)
BodyOfLoop;
endwhile;
?>
(OR)
<?
while (condition) :
?>
HTML instructions
<? endwhile ?>

CS3001
Lecture 13 / Slide 27

do - while
<?
$i = 0;
do {
print $i;
} while ($i>0);
?>
Output:
0

CS3001
Lecture 13 / Slide 28

String Functions
Function

Description

chop()

Alias of rtrim()

chr()

Returns a character from a specified


ASCII value

echo()

Outputs strings

join()

Alias of implode()

ltrim()

Strips whitespace from the left side of a


string

ord()

Returns the ASCII value of the first


character of a string

print()

Outputs a string

printf()

Outputs a formatted string

rtrim()

Strips whitespace from the right side of


a string

CS3001
Lecture 13 / Slide 29

String Functions
Function

Description

str_replace()

Replaces some characters in a string (casesensitive)

strcmp()

Compares two strings (case-sensitive)

strlen()

Returns the length of a string

strpos()

Returns the position of the first occurrence


of a string inside another string (casesensitive)

strrev()

Reverses a string

strtolower()

Converts a string to lowercase letters

strtoupper()

Converts a string to uppercase letters

substr()

Returns a part of a string

trim()

Strips whitespace from both sides of a string

CS3001
Lecture 13 / Slide 30

echo(), print()
void print (string arg)
print("Hello World"); //Hello World
print "print() also works without parentheses.";
//print() also works without parentheses.
void echo ( string arg1 [, string argn...])
$foo=foobar;
$bar=barbaz;
echo $foo,$bar; // foobarbarbaz

CS3001
Lecture 13 / Slide 31

chop() / rtrim() (1)


 chop(string [, charlist])
 rtrim(string [, charlist])
Strip whitespace (or other characters) from the end of a string.

The following characters are removed from the end of


the string if the charlist parameter is empty:
"\0" - ASCII 0, NULL
"\t"
- ASCII 9, a tab
"\n" - ASCII 10, a new line
"\x0B" - ASCII 11, a vertical tab.
"\r" - ASCII 13, a carriage return
""
- ASCII 32, an ordinary white space

CS3001
Lecture 13 / Slide 32

rtrim() (2)
<?php
$text = "\t\tThese are a few words :) ...\t ";
$trimmed = rtrim($text);
print "$trimmed - 1st print\n";
// These are a few words :) ... - 1st print
$trimmed = rtrim($text," \t.");
print "$trimmed - 2nd print\n";
// These are a few words :) - 2nd print
$clean = rtrim($trimmed,"\0x00 .. \0x1F");
// trim the ASCII control characters at the end of $trimmed
// (from 0 to 31 inclusive)

print "$clean - 3rd print\n";


// There are a few words :) - 3rd print
?>

CS3001
Lecture 13 / Slide 33

ltrim(), trim()
 string ltrim ( string str [, string charlist])

Strip whitespace (or other characters) from the


beginning of a string.
 string trim ( string str [, string charlist])

Strip whitespace (or other characters) from the


beginning and end of a string

CS3001
Lecture 13 / Slide 34

chr()
 string chr ( int ascii)

Returns a one-character string containing the character


specified by ascii.
<?
$str=abc;
$str.=chr(65);
echo $str;
?>
Output:
abcA

CS3001
Lecture 13 / Slide 35

ord()
 int ord ( string string)

Return ASCII value of character


$str=A;
if( ord($str) == 65 )
{
echo "The character of A;
}
Output:
The character is A

CS3001
Lecture 13 / Slide 36

strcmp()
 int strcmp (string str1, string str2)

Binary safe string comparison


Returns

< 0 if str1 is less than str2;


> 0 if str1 is greater than str2,
0 if they are equal.

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

CS3001
Lecture 13 / Slide 37

strlen()
 int strlen ( string str)

Get string length


<?
$str=hello;
echo strlen($str);
?>

//5

CS3001
Lecture 13 / Slide 38

strpos(), strrpos()
 int strpos(string str, string search [, int offset])

Find position of first occurrence of a string


 int strrpos ( string str, char search)

Find position of last occurrence of a char in a string


<?
$str="This is a string is a string";
echo strpos($str,"is,3),"<br>"; //5
echo strrpos($str,"s"),"<br>";
?>

//22

CS3001
Lecture 13 / Slide 39

strrev()
 string strrev ( string str)

Reverse a string
<?
echo strrev("Hello world!");
?>
Output:
"!dlrow olleH"

CS3001
Lecture 13 / Slide 40

strtolower(), strtoupper()
 string strtolower ( string str)

Make a string lowercase


$str = "Mary Had A Lamb & LOVED It So";
$str = strtolower($str);
print $str; //mary

had a lamb & loved it so

 string strtoupper ( string str)

Make a string uppercase


$str = strtoupper($str);
print $str; //MARY

HAD A LAMB & LOVED IT SO

CS3001
Lecture 13 / Slide 41

substr()
 string substr ( string string, int start [, int
length])

Return part of a string


$str=This is a string
echo substr($str,5);

//is a string

echo substr($str,5,6);

//is a s

CS3001
Lecture 13 / Slide 42

str_replace()
 str_replace(search_str, replace_str, str, count);

Replace all occurrences of the search string with the


replacement string
$str=This is a string;
echo str_replace(s,z,$str,$a); //Thiz iz a
ztring
echo $a;

//3

CS3001
Lecture 13 / Slide 43

Date and time function


string date ( string format [, int timestamp])
Format a local time date
1st arg Format characters:- d, D, m, M, y, Y, h, i, s, ...
2nd arg mktime(hour,minute,second,month,day,year,is_dst)
<?
echo(date("M-d-Y",mktime(0,0,0,12,36,2001)). \t");
echo(date("M-d-Y",mktime(0,0,0,14,1,2001)). \t");
echo(date("M-d-Y",mktime(0,0,0,1,1,2001)).\t");
echo(date("M-d-Y",mktime(0,0,0,1,1,99)));
?>
//Jan-05-2002

Feb-01-2002

Jan-01-2001

Jan-01-1999

$today = date("m.d.y"); // 03.10.01


$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17
m is month

CS3001
Lecture 13 / Slide 44

Arrays

CS3001
Lecture 13 / Slide 45

Arrays
Easiest way
$colorList=array("red","green","blue","black","white");

Initialise array elements one-by-one


$colorList[0] = "red";
$colorList[1] = "green";
$colorList[2] = "blue";
$colorList[3] = "black";
$colorList[4] = "white";

Array can be created like this also


$colorList[] = "red";
$colorList[] = "green";
$colorList[] = "blue";
$colorList[] = "black";
$colorList[] = "white";

CS3001
Lecture 13 / Slide 46

Printing arrays
echo $colorList[0];

//red

for ($i=0;$i<=4;$i++){
echo $colorList[$i];
}
foreach ($colorList as $value) {
echo $value;
}
// Elements are pass by value

Output:
red
green
blue
black
white

CS3001
Lecture 13 / Slide 47

1-based index with array()


$firstquarter = array(
1 => 'January', 'February', 'March );
print_r($firstquarter);

Output:
Array (
[1] => January
[2] => February
[3] => March
)

CS3001
Lecture 13 / Slide 48

Automatic index with array()


 array array ( [mixed ...])
Create an array
$array=array(1,1,1,1,1,8=>1,4=>1,19,3=>13);
print_r($array);
Output:

0 1

Array

1 11

1 11

1 1

13 1

[0] => 1
[1] => 1
[2] => 1
[3] => 13
[4] => 1
[8] => 1
[9] => 19
)

19
1

19

CS3001
Lecture 13 / Slide 49

Array
(

2-dimensional array (1)

[Griffin] => Array


(

$families = array (

[0] => Peter

"Griffin"=>array ( "Peter", "Lois", "Megan" ),

[1] => Lois

"Quagmire"=>array ( "Glenn" ),
"Brown"=>array ("Cleveland","Loretta","Junior)
);

[2] => Megan


)

[Quagmire] => Array

print_r($families);

(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)

CS3001
Lecture 13 / Slide 50

2-dimensional array (2)


$myLists['colors'] = array("apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",
"wall"=>"white");
$myLists['cars'] = array("BMW"=>"M6",
"Mercedes"=>"E 270 CDI",
"Lexus"=>"IS 220d",
"Mazda"=>"6",
"Toyota"=>"Avensis");
echo $myLists['cars']['Toyota']; //Avensis

CS3001
Lecture 13 / Slide 51

Associate arrays (1)

$colorList = array(
"apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",
"wall"=>"white
);
Array created one by one elements like:
$colorList["apple"] = "red";
$colorList["grass"] = "green";
$colorList["sky"] = "blue";
$colorList["night"] = "black";
$colorList["wall"] = "white";

CS3001
Lecture 13 / Slide 52

Associate arrays (2)


You can mix your array and use numbers and strings in the same
list like this:
$colorList["apple"] = "red";
$colorList[5] = "green";
$colorList["sky"] = "blue";
$colorList["night"] = "black";
$colorList[22] = "white";

CS3001
Lecture 13 / Slide 53

sizeof(), unset(), isset()


sizeof : no of elements are in the array.
echo sizeof($colorList);
unset: remove an element from the array.
unset($colorList["sky"]);
isset: check whether an array has a requested element
if (isset($colorList["grass"]))
echo "OK";

CS3001
Lecture 13 / Slide 54

Array functions

array_combine
array_push
array_pop
array_unshift array_shift
array_flip
array_unique
array_key_exists
array_reverse
array_splice
array_walk
array_walk_recursive
each

CS3001
Lecture 13 / Slide 55

array_combine, array_push & array_pop


<?php
$a1=array("a","b","c","d");
$a2=array("Cat","Dog","Horse","Cow");
$a3=array_combine($a1,$a2);
print_r($a3);
# Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow )

array_push($a3,Eagle","Bird");
print_r($a3);
# Array ([a] => Cat [b] => Dog [c] => Horse [d] => Cow
[0] => Eagle [1] => Bird )
array_pop($a3);
print_r($a3);
# Array ([a] => Cat [b] => Dog [c] => Horse [d] => Cow
[0] => Eagle )
?>

CS3001
Lecture 13 / Slide 56

array_unshift
& array_shift
<?
$a=array("a"=>"Cat","b"=>"Dog");
$return_value = array_unshift($a,"Horse");
print_r($a);
# Array ( [0] => Horse [a] => Cat [b] => Dog )

print $return_value; # 3 (length of array)


echo array_shift($a); # Horse
print_r ($a);
# Array ( [a] => Cat [b] => Dog )
$b=array(0=>"Cat",1=>"Dog"); # numeric keys
array_unshift($b,"Horse");
print_r($b);
#Array ( [0] => Horse [1] => Cat [2] => Dog )
echo array_shift($b) # Horse

print_r($b);
#Array ( [0] => Cat [1] => Dog )

?>

CS3001
Lecture 13 / Slide 57

array_flip, array_unique & array_key_exists


<?

$a=array(0=>"Dog",1=>"Cat",2=>"Horse");
# keys & values are exchanged

print_r(array_flip($a));
# Array ( [Dog] => 0 [Cat] => 1 [Horse] => 2 )

$b=array(0=>"Dog",1=>"Cat",2=>Dog");
print_r(array_flip($b));
# Array ( [Dog] => 2 [Cat] => 1 )

$c=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
print_r(array_unique($c));
# Array ( [a] => Cat [b] => Dog )
if (array_key_exists("a",$a))
{
echo "Key exists!";
# Key exists!
}
else
{
echo "Key does not exist!";
} ?>

CS3001
Lecture 13 / Slide 58

array_reverse,
array_splice
<?
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r(array_reverse($a)); # by default false
# Array ( [c] => Horse [b] => Cat [a] => Dog )

print_r(array_reverse($a, true));
# by default false as shown above. Not working in some
versions
# Array ( [a] => Horse [b] => Cat [c] => Dog )

$a1=array(0=>"Dog",1=>"Cat",2=>"Horse,3=>"Bird");
$a2=array(0=>"Tiger",1=>"Lion");
print_r(array_splice($a1,0,2,$a2));
# Array ( [0] => Dog [1] => Cat )

print_r($a1);
# Array ( [0] => Tiger [1] => Lion [2] => Horse [3] => Bird)

?>

CS3001
Lecture 13 / Slide 59

array_walk & array_walk_recursive

<?
function myfunction($value,$key,$p)
{
a has the value Cat
echo "$key $p $value<br />";
b has the value Dog
}
c has the value Horse
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction","has the value");
?>
<?
The key a has value Cat
function myfunction($value,$key)The key b has value Dog
The key 1 has value Bird
{
echo "The key $key has value $value<br />";
}
$a1=array("a"=>"Cat","b"=>"Dog");
$a2=array($a1,"1"=>"Bird");
array_walk_recursive($a2,"myfunction");
?>

CS3001
Lecture 13 / Slide 60

join() / implode()
 string implode ( string glue, array pieces)

Returns a string containing a string representation of all


the array elements in the same order, with the glue
string between each element.
<?php $array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
print $comma_separated;
?>
Output:
lastname,email,phone

CS3001
Lecture 13 / Slide 61

explode()
 array explode ( string separator, string string [, int
limit])
 Split a string by string
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);

$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user,$pass,$uid,$gid,$gecos,$home,$shell) =
explode(":",$data);

CS3001
Lecture 13 / Slide 62

split()
 if you don't require the power of regular expressions, it
is faster to use explode(), which doesn't incur the
overhead of the regular expression engine.
 split string into array by regular expression
 array split ( string pattern, string string [, int
limit])

CS3001
Lecture 13 / Slide 63

array_keys()
array array_keys (array array, mixed [search_element])
$great_wines = array (
"Australia" => "Clarendon Hills 96",
"France" => "Comte Georges de Vogue 97",
"Austria" => "Feiler Artinger 97");
$great_labels = array_keys($great_wines);
// $great_labels=array ("Australia", "France", "Austria");

CS3001
Lecture 13 / Slide 64

array_values()
 array array_values(array array)
$great_wines = array (
"Australia" = "Clarendon Hills 96",
"France = "Comte Georges de Vogue 97",
"Austria = "Feiler Artinger 97");
$great_labels = array_values($great_wines);
// $great_labels = array ("Clarendon Hills 96",
"Comte Georges de Vogue 97",
"Feiler Artinger 97");

CS3001
Lecture 13 / Slide 65

array_merge()
array_merge (array array1, array array2, . . ., array
arrayN)

The array_merge() function merges 1 to N arrays together, appending


each toanother in the order in which they appear as input parameters.
$arr_1 = array ("strawberry", "grape", "lemon");
$arr_2 = array ("banana", "cocoa", "lime");
$arr_3 = array ("peach", "orange");
$arr_4 = array_merge ($arr_2, $arr_1, $arr_3);

//$arr_4 = array("banana", "cocoa", "lime",


"strawberry, "grape", "lemon", "peach",
"orange");

CS3001
Lecture 13 / Slide 66

Sorting
 bool sort (array array)

2nd optional argument


int $sort_flags
SORT_REGULAR
SORT_NUMERIC
SORT_STRING

sorting array elements from lowest to highest value


 bool rsort (array array)

Sorts the array by its values in a reverse order


 bool asort (array array)

Sorts the array by its values


 bool arsort (array array)

Sorts the array by its values in reverse order


 bool ksort (array array)

Sorts the array by its keys


 bool krsort (array $array)

Sorts the array by its keys in a reverse order

CS3001
Lecture 13 / Slide 67

each()
<?php
$countries = array ( "ca" => "Canada",
"cr" => "Costa Rica",
"de" => "Germany",
"uk" => "United Kingdom",
"us" => "United States");
while (list ($key, $val) = each ($countries)) {
echo "Element $key equals $val<BR>\n";
}
?>

Output:
Element
Element
Element
Element
Element

ca
cr
de
uk
us

equals
equals
equals
equals
equals

Canada
Costa Rica
Germany
United Kingdom
United States

CS3001
Lecture 13 / Slide 68

strip_tags()
string strip_tags(string string [,string allowable_tags])
$user_input = "i just <b>love</b> PHP and <i>gourmet</i>
recipes!";
$stripped_input = strip_tags($user_input);

// $stripped_input = "I just love PHP and gourmet recipes!";

CS3001
Lecture 13 / Slide 69

strtok()
 string strtok (string string, string tokens)
$info = "WJ Gilmore:mor@hotmail.com|Columbus,Ohio";
$tokens = ":|,";
$tokenized = strtok($info, $tokens);

// print out each element in the $tokenized array


while ($tokenized) :
echo "Element = $tokenized<br>";

Element =WJ Gilmore


$tokenized = strtok ($tokens); Element = mor@hotmail.com
endwhile;
Element = Columbus
Element = Ohio
Note strtok does not take the first argument on subsequent executions

CS3001
Lecture 13 / Slide 70

Constants
 Value cannot be changed or undefined during the execution of
the script
 Boolean, integer, float and string
 A valid constant name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.
 Should not prepend a constant with a $
 Can also use the function constant() to read a constant's
value
 Use get_defined_constants() to get a list of all defined
constants
define("FOO_BAR", "something more");
echo FOO_BAR //something more

CS3001
Lecture 13 / Slide 71

Variables vs Constants
 Constants do not have a dollar sign ($) before them
 Constants may only be defined using the define()
function, not by simple assignment
 Constants may be defined and accessed anywhere
without regard to variable scoping rules
 Constants may not be redefined or undefined once they
have been set
 Constants may only evaluate to scalar values

CS3001
Lecture 13 / Slide 72

include
 The include() function takes all the text in a specified
file and copies it into the file that uses the include
function.
// menu.php
<html> <body>
<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">ContactUs</a>
// home.php
<?php include("menu.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body> </html>

CS3001
Lecture 13 / Slide 73

require
 The require() function is identical to include(), except that it
handles errors differently.
 The include() function generates a warning (but the script will
continue execution) while the require() function generates a fatal
error (and the script execution will stop after the error).
<html> <body>
<?php require("wrongFile.php");
echo "Hello World!"; ?>
</body> </html>

CS3001
Lecture 13 / Slide 74

Regular Expressions

CS3001
Lecture 13 / Slide 75

ereg
 int ereg(string pattern, string source, array [regs]);

if (ereg("^.+@.+\\..+$", $email)) {
echo ("E-mail address is valid.");
}
else{
echo ("Invalid e-mail address.");
}

CS3001
Lecture 13 / Slide 76

ereg example
if (ereg("^(.+)@(.+)\\.(.+)$", $email, $arr))
{
echo ("E-mail address is valid. <BR>\n" .
"E-mail address: $arr[0] <BR>\n" .
"Username: $arr[1] <BR>\n" .
"Domain name: $arr[2] <BR>\n" .
"Top-level domain name: $arr[3] <BR>\n);
}
else
{
echo ("Invalid e-mail address. <BR>\n");
}

CS3001
Lecture 13 / Slide 77

eregi
 eregi() behaves identically to ereg(), except it ignores
case distinctions when matching letters.
 case insensitive

CS3001
Lecture 13 / Slide 78

ereg_replace() and eregi_replace()


 string ereg_replace(string pattern, string
replacement, string string);
$str = "Then the pair followed Pa to
Manhasset";
$pat = "followed";
$repl = "FOLLOWED";
echo (ereg_replace($pat, $repl, $str));

//Then the pair FOLLOWED Pa to Manhasset

CS3001
Lecture 13 / Slide 79

ereg_replace example
$str = "Where he still held the cash as an
asset";
$pat = "c(as)h";
$repl = "C\\1H";
echo (ereg_replace($pat, $repl, $str));

// Where he still held the CasH as an asset

CS3001
Lecture 13 / Slide 80

Forms

CS3001
Lecture 13 / Slide 81

welcome.html (1)
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
Submitted URL:
http://www.w3schools.com/welcome.php?name=P
eter&age=37

CS3001
Lecture 13 / Slide 82

welcome.php (2)
Welcome <?php echo $_GET["name"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
(OR)
Welcome <?php echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years
old!

CS3001
Lecture 13 / Slide 83

order.html (1)
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />
</form>
</body></html>

CS3001
Lecture 13 / Slide 84

process.php (2)
<html><body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?>
</body></html>
Output:
You ordered 6 brushes.
Thank you for ordering from Tizag Art Supplies!

CS3001
Lecture 13 / Slide 85

Functions

CS3001
Lecture 13 / Slide 86

Passing arrays to functions


<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2,3));
?> // 1 + 2 = 3

CS3001
Lecture 13 / Slide 87

Passing function parameters by reference


<?php
function add_some_extra(&$string)
{
$string .= 'and extra.';
}
$str = 'This string, ';
add_some_extra($str);
echo $str;
?>

//This string, and extra.

CS3001
Lecture 13 / Slide 88

Use of default parameters in functions


<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

CS3001
Lecture 13 / Slide 89

Using non-scalar types as default values


<?php
function makecoffee($types = array("cappuccino"), $coffeeM
aker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with
$device.\n
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

CS3001
Lecture 13 / Slide 90

Use of return()
<?php
function square($num)
{
return $num * $num;
}
echo square(4);
?>

// outputs '16'

CS3001
Lecture 13 / Slide 91

Returning an array to get multiple values


<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

CS3001
Lecture 13 / Slide 92

Returning a reference from a function


<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>

CS3001
Lecture 13 / Slide 93

<HTML> <BODY>
<?
function createBoard ($lines,
{
$j=1;
echo ("<TABLE ALIGN=CENTER
while ($j<=$lines){
echo ("<TR>");
$k=1;
while ($k<=$cols){
if (($j+$k)%2>0)
echo ("<TD WIDTH=30
else
echo ("<TD WIDTH=30
$k++; }
echo("</TR>");
$j++; }
echo ("</TABLE><BR><BR>");
}
createBoard(8,8);
createBoard(4,4);
?>
</BODY></HTML>

$cols)

BORDER=1 CELLSPACING=0>");

HEIGHT=30 BGCOLOR=#000000> </TD>");


HEIGHT=30 BGCOLOR=#FFFFFF> </TD>");

CS3001
Lecture 13 / Slide 94

Output

CS3001
Lecture 13 / Slide 95

File functions












fopen
fread
fwrite
fclose
file_get_contents
file_put_contents
filesize
is_file
unlink
copy
rename

CS3001
Lecture 13 / Slide 96

fopen(), fclose()
$file = fopen("test.txt","r");
#some code to be executed
fclose($file);
2nd arg:- r, r+, w, w+, x, x+, a, a+

CS3001
Lecture 13 / Slide 97

feof(), fgets(), fgetc()


Reading a File Line by Line
<?
$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 />";

?>

Reading a File Character by Character

fclose($file);

while (!feof($file))
{
echo fgetc($file);
}

CS3001
Lecture 13 / Slide 98

fread()
 string fread ( resource $handle , int $length )
 <?
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filena
me));
fclose($handle);
?>

CS3001
Lecture 13 / Slide 99

fwrite()
fwrite(file,string,length)
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
$cat testFile.txt
Bobby Bopper
Tracy Tanner

CS3001
Lecture 13 / Slide 100

file_get_contents(), file_put_contents()
Reads entire file into a string
string file_get_contents ( string filename [, int
$flags [, resource $context [, int $offset [, int
$maxlen ]]]] )

Write a string to a file


int file_put_contents ( string filename, mixed data [,
int flags [, resource context]])

CS3001
Lecture 13 / Slide 101

touch(), unlink(), copy(), rename()


bool touch (string $filename[,int $time[,int $atime]])

Sets access and modification time of file


If the file does not exist, it will be created
bool unlink ( string filename)

Deletes a file
bool copy(string source, string destination);
$filename = "text.txt";
copy($filename, "../temp/" . $filename);
//Copies to /temp/text.txt
bool rename(string oldname, string newname);

CS3001
Lecture 13 / Slide 102

rewind(), fseek(), feof()


 int rewind(int fp);
Rewind the position of a file pointer. The return value is true
on success, false on failure
 int fseek(int fp, int offset);


The fp argument is of course the file handle; the offset is the


number of bytes or characters from the beginning of the file.
 int feof(int fp);


while (!feof($file)) {

CS3001
Lecture 13 / Slide 103

Directory functions







opendir
readdir
mkdir
chdir
rmdir
is_dir

CS3001
Lecture 13 / Slide 104

Directory functions - opendir(), is_dir(),


readdir(), filetype(), closedir()
<?php $dir = "/tmp/";
// Open a known directory, and proceed to read its
contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
print "filename: $file : filetype: " .
filetype($dir . $file) . "\n"; //false, fifo, char, dir,
block, link, file, socket, unknown
}
closedir($dh);
}
}/* http://gnuisance.net/blog/t/2007/file-types.html
?>

*/

CS3001
Lecture 13 / Slide 105

mkdir(), chdir(), rmdir()


bool rmdir ( string dirname)

Removes directory
bool mkdir ( string pathname [, int mode [,
bool $recursive ]])

Makes directory mkdir ("/path/to/my/dir", 0700);


bool chdir ( string $directory )

Change directory

CS3001
Lecture 13 / Slide 106

Determining File Attributes (1)


 bool file_exists(string filename);


if exists -- return true

 int filesize(string filename);




return file size in bytes or FALSE in case of error

 string filetype(string filename);




return string fifo,char,dir,block,link,file

CS3001
Lecture 13 / Slide 107

Determining File Attributes (2)


 bool is_dir(string filename);
 bool is_file(string filename);
 bool is_link(string filename);
 bool is_readable(string filename);
 bool is_writeable(string filename);
 bool is_executable(string filename);

CS3001
Lecture 13 / Slide 108

DB Connectivity

CS3001
Lecture 13 / Slide 109

Connect to MySQL Database


<?php
$dbhost = 'db.php-mysql-tutorial.com:3306';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error
connecting to mysql');
$dbname = 'petstore';
mysql_select_db($dbname,$conn);
?>

<?php
// it does nothing but closing a mysql database connection

mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 110

Creation
of
DB
&
Tables
<?php
$conn=mysql_connect('localhost','root','');
$db_list = mysql_list_dbs($conn);
mysql_select_db('test,$conn);
$query = 'CREATE DATABASE phpcake';
$result = mysql_query($query);
echo "database created...<br>";
mysql_select_db('phpcake') or die('Cannot select database');
$query = 'CREATE TABLE contact( '.
'cid INT NOT NULL AUTO_INCREMENT, '.
'cname VARCHAR(20) NOT NULL, '.
'cemail VARCHAR(50) NOT NULL, '.
'csubject VARCHAR(30) NOT NULL, '.
'cmessage TEXT NOT NULL, '.
'PRIMARY KEY(cid))';
$result = mysql_query($query);
echo "table created...<br>";
mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 111

Retrieve Data (1)


<?php
$conn=mysql_connect('localhost','root','');
mysql_select_db('test,$conn);
$query = "SELECT name, subject, message FROM
contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
//while($row = mysql_fetch_assoc($result))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 112

Retrieve Data (2)


<?php
$conn=mysql_connect('localhost','root','');
mysql_select_db('test,$conn);
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_NUM))
// numeric indexes
{
echo "Name :{$row[0]} <br>" .
"Subject : {$row[1]} <br>" .
"Message : {$row[2]} <br><br>";
}
mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 113

Retrieve Data (3)


<?php
$conn=mysql_connect('localhost','root','');
mysql_select_db('test,$conn);
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while(list($name,$subject,$message)= mysql_fetch_row($result))

{
echo "Name :$name <br>" .
"Subject : $subject <br>" .
"Message : $row <br><br>";
}
mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 114

Retrieve Data (4)


<?php
$conn=mysql_connect('localhost','root','');
mysql_select_db('test,$conn);
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row
{
$name
$subject
$message

= mysql_fetch_row($result))
= $row[0];
= $row[1];
= $row[2];

echo "Name :$name <br>" .


"Subject : $subject <br>" .
"Message : $row <br><br>";
}
mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 115

Insert
into table
<html>
<head><title>Add New MySQL User</title></head>
<body>
<?
if(isset($_POST['add']))
{
$conn=mysql_connect('localhost','root','');
mysql_select_db('test,$conn);
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO user (host, user, password,
select_priv,
insert_priv, update_ priv) VALUES ('localhost',
'$username',
PASSWORD('$password'), 'Y', 'Y', 'Y')";
mysql_query($query) or die('Error, insert query
failed');
$query = "FLUSH PRIVILEGES";
mysql_query($query) or die('Error, insert query
failed');
mysql_close($conn);
echo "New MySQL user added";
}

CS3001
Lecture 13 / Slide 116

Insert
elseinto table contd...
{
?>
<form method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Username</td>
<td><input name="username" type="text" id="username"></td>
</tr>
<tr>
<td width="100">Password</td>
<td><input name="password" type="text" id="password"></td>
</tr>
<tr>
<td width="100">&nbsp;</td> <td>&nbsp;</td>
</tr>
<tr>
<td width="100">&nbsp;</td>
<td><input name="add" type="submit" id="add" value="Add New
User"></td>
</tr>
</table>
</form>
<?
}
?>
</body>
</html>

CS3001
Lecture 13 / Slide 117

Update Query
<?php
$conn=mysql_connect('localhost','root','');
$db_list = mysql_list_dbs($conn);
mysql_select_db('test,$conn);
$query = "update employee set salary=10000 where fname='aaa'";
$result=mysql_query($query) or die('Error, insert query
failed');
if($result) {
echo "Successful";
}
else {
echo "Error";
}
?>

CS3001
Lecture 13 / Slide 118

Delete Query
<?php
$conn=mysql_connect('localhost','root','');
$db_list = mysql_list_dbs($conn);
mysql_select_db('test,$conn);
$query = "delete from employee where salary=10000'";
$result=mysql_query($query) or die('Error, delete query
failed');
if($result) {
echo "Successful<br>";
}
else {
echo "Error<br>";
}
mysql_close($conn);
?>

CS3001
Lecture 13 / Slide 119

Dropping DB
<?php
$conn=mysql_connect('localhost','root','');
$db_list = mysql_list_dbs($conn);
mysql_select_db('test,$conn);
$query = 'DROP DATABASE phpcake';
$result = mysql_query($query);
echo "database deleted";
mysql_close($conn);

?>

CS3001
Lecture 13 / Slide 120

Execute Query From File


<?php
$conn=mysql_connect('localhost','root','');
$db_list = mysql_list_dbs($conn);
mysql_select_db('test,$conn);
$queryFile = 'myquery.txt';
$fp
= fopen($queryFile, 'r');
$query = fread($fp, filesize($queryFile));
fclose($fp);
$result = mysql_query($query);
echo "query loaded from file and executed<br>";

?>
myquery.txt
update employee set salary=10000 where fname='aaa';

CS3001
Lecture 13 / Slide 121

References
 http://www.tizag.com/phpT/
 http://www.w3schools.com/PHP/DEfaULT.asP
 http://in2.php.net/tut.php