Você está na página 1de 196

LOCALIZATION OF E-GOVERNANCE PROJECT

PRESENTATION ON ADVANCED PHP


(26 NOV 5 DEC, 2008)

Submitted to: Department of Information Technology,


Ministry of Information and Communication, Royal Government of Bhutan

Submitted by:

Er. Vishanta Rayamajhi International ICT Expert

CONTENTS
1. Abstract 2. Acknowledgement 3. Web programming in PHP 4. 5. 6. 7. 8. 9. PHP JavaScript AJAX OOP MySQL PostgreSQL PEAR DB Abstraction Captcha CSS XML RSS Feeds GD library Smarty Web Security

AJAX Example Classes and Objects Example PHP and PostgreSQL with PEAR DB Examples Captcha Example CSS Example PHP XML Examples

10. RSS Feeds Example 11. Image / Graphics handling in PHP Example 12. Project work on CRUD functionality in single file Sample 1 13. Project work on CRUD functionality in multiple files Sample 2 14. Training Feedback Form and Consultant Contact Details

ABSTRACT

The training session held during 26 November to 5 December, 2008 aims towards capacity building of ICT Officers in various Ministries and Autonomous Agencies including Department of Information Technology, DIT, MoIC working in Royal Government of Bhutan. This is mainly the basis and foundation of e-platform and e-service prototypes development in Zend Framework as a part of Localization on E-Governance project funded by UNDP. Today, PHP is the most widely used programming language on the Web, with over 60 percent of all web applications written in PHP. It is installed on over 30 million domain servers approximately. The number of developer using PHP has now reached over 10 million. Its simplicity is what made PHP so successful. Simplicity equals less code. Developers and companies have been developing projects with PHP in a fraction of the time it would take another language. The future of PHP is very bright. Leading platform vendors such as IBM, Oracle, MySQL, Intel, and, most recently, Red Hat have all endorsed it. The new Collaboration Project initiated by Zend Technologies rallies many leading companies and community members around new open source initiative aimed at taking PHP to the next level of creating an industrial-grade, de facto standard PHP web application development and deployment environment. One of the Projects open initiatives is Zend PHP Framework. The training comprises of basic as well as advanced usage of PHP (PHP: Hypertext Preprocessor). The participants were mostly beginners, fresh graduates with little intermediate knowledge in web development platform. The training modules were structured in such a way that the participants were fully engaged in carrying out certain practical assignments in parallel with theoretical session. The participants were assigned to develop a small application which included login authentication using session handling and CRUD (Create, Retrieve, Update, and Delete) functionalities using back-end database (MySQL). Paragraphs below briefly describe the details of the content of the training document.

This document presents the introduction to programming in PHP. It contains both an introduction to programming and an introduction to PHP for beginner as well as intermediate programmers. The document begins with the basics of PHP and describes the basic features of PHP with examples of their use. Participants were also made familiar with latest PostgreSQL database and handling DB activities using PHP. The document goes on to describe the most common usage of PHP. It shows how to write scripts for Web sites, file manipulation, databases, sessions, and other common tasks. It provides techniques, shortcuts and warns against common errors. Both beginners and experienced programmers can write useful scripts for many common applications in a very short time. Some major topics such as XML and RSS Feeds, AJAX, Captcha, PHP 5 Classes and Objects, PEAR Repository, GD Library, Smarty, etc. were covered which are the prominent functionality the modern web offers. At length, Web Security vulnerabilities were covered and several ways to combat the security threats and loopholes. The security topics dealt were not only covered from web application development perspective, but, from web server and network perspective as well to make the picture in a broader scope.

ACKNOWLEDGEMENTS

I would like to thank Department of Information Technology, MoIC and UNDP to help organize this institutional capacity building training on PHP for ICT Officers from various Ministries and autonomous agencies as a part of UNDP funded project on Localization of E-Governance held on 26 Nov to 5 Dec, 2008. I would also like to thank all the ICT Officers for their participation and their ministries and agencies in rendering their kindness and support to conduct the national capacity building campaign. My special thank to Mr. Jigme Tenzing, Head of Application Division, DIT to facilitate the training session and Mr. Tashi Daw, Project Manager of Localization of E-Governance, DIT and Mr. Devi Bhakta Suberi, M.Sc. Computer Technology, Attachment Candidate who actively participated in the entire training session.

Web Programming in PHP


PHP JavaScript AJAX OOP MySQL PostgreSQL PEAR Captcha CSS XML RSS Feeds GD library Smarty Web Security

Vishanta Rayamajhi International ICT Expert +977 98510 21580 vishanta.rayamajhi@gmail.com

Contents
PHP History, Basics, Environments setup for application dev. Language Reference (Syntax, Data Types, Variables, Expression, etc.) Control Structures (if, switch, while, for, foreach, break, continue) Functions (user-defined, in-built) Arrays and Array Functions (single, multi, associative) Strings Numbers and Math Operations Dates and Times PHP Includes and SSI CGI Environment Variables Form Handling Server-side validations
2

Contents (contd.)
Client-side validations using JavaScript AJAX (XMLHttpRequest, Prototype, jQuery, etc.) Passing information across pages File ploads HTTP Headers Finding out about your PHP Environment Filesystem and Directory functions Maintaining Sessions with PHP Cookies Sending Emails PHP 4 Classes and Objects PHP 5 Classes and Objects
3

Contents (contd.)
SQL Basics MySQL PHP and MySQL (connection, forms, queries, error handling, etc.) PostgreSQL PHP and PostgreSQL (connection, forms, queries, etc.) PEAR (PEAR Intro, PEAR Package, PEAR Coding Style) Captcha CSS (Cascading Style Sheets) Introduction to XML PHP and XML RSS Feeds Image / Graphics Handling in PHP (Introduction to GD library) Smarty Security (Possible attacks and threats, SQL Injection, XSS attack, etc.)
4

PHP History
PHP originally stood for Personal Home Page It started out, in 1994, as a simple preprocessor of HTML files
built by Rasmus Lerdorf

Later officially named as PHP : Hypertext Pre-Processor recursive naming Syntax similar to C and Perl

Enable PHP in HTTP (Web) Servers


PHP is available in Windows and all types of Unix environments It is supported by Apache, AOLServer, Roxen and IIS Httpd daemon / IIS recognizes a file with the suffix .php as a PHP file
6

What is PHP?
PHP is an open source, server-side, HTMLembedded scripting language used to create dynamically generated web pages Server-side technology Case-sensitive PHP is a loosely typed language PHP is CGI (Common Gateway Interface) alternative CGI program is executed by Web server in response to a request made by Web browser
7

A first PHP file


<html> <head> <title>PHP Training</title> </head> <body> <?php echo <p>PHP Training at DIT, MoIC, Bhutan</p>"; ?> </body> </html> Save as <filename>.php

How PHP files Are Processed


The httpd demon simply copies regular HTML content in the .php file to the message body that will be sent to a client which requests the .php file The tag is of the form
<?php ?>

The text inside the tag is PHP code


<?php echo <p>Hello World</p>"; ?>

The httpd demon executes this PHP code and copies the output text, generated by this PHP code, to the message body that will be sent to the client Thus, the client would see only
<p>Hello World</p>
9

PHP Tags
In the example just seen, the PHP tag was
<?php ?>

This is the best PHP tag to use it is the one which works best if we are also using XML, because it avoids conflicts with XML Processing Instructions The following tags are also used
<? ?> <% %> <script language=php> </script>

10

Variables in PHP
Variables in PHP are denoted by a dollar sign followed by the name of the variable
$a, $b

A variable name is case-sensitive, like C A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores, like C again

11

Example of Variables
<html> <head> <title>Greetings</title> </head> <body> <h1>Greetings</h1> <p> <?php $person = Rasmus"; $Person = Lerdorf"; echo "Hello $person and $Person"; ?> </p> </body> </html>
12

Automatic Variables in PHP


One of the main benefits of PHP is that it provides lots of variables automatically Consider, for example, the .php file on the next slide, $_SERVER[HTTP_USER_AGENT]
It produces the output on the following two slides when viewed by MSIE x.x and Mozilla x.x

13

Example of Automatic PHP Variable


<html> <head> <title>Your browser</title> </head> <body> <h1>Your Browser</h1> <p> You are using <?php echo $_SERVER[HTTP_USER_AGENT]; ?> to view this page. </p> </body> </html>
14

Example of Automatic PHP Variable (cont.)

15

Example of Automatic PHP Variable (cont.)

16

Data Types in PHP


PHP supports following primitive data types
There are four scalar types
boolean integer floating-point number string

There are two structured / compound types


array object

17

Data Types in PHP (cont.)


The programmer does not need to specify the type of a variable
a variables type is determined from the context of its usage

18

Booleans
The boolean data type admits two values
true (case-insensitive) false (case-insensitive)

Example
$itIsRainingToday = true; $thePrinterIsBusy = True; $theQueueIsEmpty = FALSE;
19

Integers
Integers can be specified in decimal, hexadecimal or octal notation, optionally preceded by a sign In octal notation, the number must have a leading 0 In hexadecimal notation, the number must have a leading 0x. Examples $a = 1234;# decimal number $a = 0123;# octal number (i.e., 83 decimal) $a = -123;# a negative number $a = 0x1B;# hexadecimal number (i.e., 27 decimal)
20

Integers (cont.)
The maximum size of an integer is platform-dependent, but usually its 32 bits signed about 2,000,000,000 PHP does not support unsigned integers.

21

Floating Point Numbers


Specified using any of these forms $a = 1.234; $a = 1.2e3; $a = 7E-10; The maximum size of a float is platformdependent, although most support a maximum of about 1.8e308 with a precision of roughly 14 decimal digits
22

Strings
Specified in three different ways
single quoted double quoted heredoc syntax

23

Single-quoted Strings
In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash
echo 'this is a simple string'; echo 'You can embed newlines in strings,

just like this.';


echo Douglas MacArthur said "I\'ll be back when leaving the Phillipines'; echo 'Are you sure you want to delete C:\\*.*?';
24

Double-quoted Strings
In double-quoted strings,
variables are interpreted to their values, and various characters can be escaped
\n linefeed \r carriage return \t horizontal tab \\ backslash \$ dollar sign \ double quote \[0-7]{1,3} a character in octal notation \x[0-9A-Fa-f]{1,2} a character in hexadecimal notation
25

Heredoc Strings
Heredoc strings are like double-quoted strings without the double quotes A heredoc string is delimited as follows The string is preceded by <<< followed by a label The string followed by a 2nd occurrence of the same label
Note: the second label must be put in the first position without any space or other characters

Example
$str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD;

26

Operators
Arithmetic Operators

27

Operators (contd.)
Assignment Operators
<?php $a = 3; $a += 5; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello "; $b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!"; ?>

28

Operators (contd.)
Comparison Operators

29

Operators (contd.)
Incrementing/Decrementing Operators

30

Operators (contd.)
Logical Operators

31

Control Structures if statement


if ($a > $b) echo "a is bigger than b"; if ($a > $b) { print "a is bigger than b"; $b = $a; } if ($a > $b) { print "a is bigger than b"; } else { print "a is NOT bigger than b"; } if ($a > $b) {print elseif ($a == {print else {print

"a is bigger than b";} $b) "a is equal to b";} "a is smaller than b;}
32

Control Structures if Statements (cont.)


Example
<html> <head><title>Your browser</title></head> <body> <h1>Your Browser</h1> <p> <?php if( strstr($_SERVER[HTTP_USER_AGENT], "MSIE") ) { echo "You are using Internet Explorer"; } ?> to view this page. </p> </body> </html>

strstr is a boolean function which checks if its 33 2nd argument is a substring of its 1st

Control Structures switch


<?php if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } switch ($i) { case 0: echo "i break; case 1: echo "i break; case 2: echo "i break; default: echo "i }

equals 0"; equals 1"; equals 2"; is not equal to 0, 1 or 2";


34

?>

Control Constructs -- while


These are just like their counterparts in C
$i = 1; while ( $i <= 10 ) { echo $i++; } --------------------------------------------------$i = 0; do { print $i;} while ($i>0);
35

Control Constructs -- for


These are just like their counterparts in C
for ($i = 1; $i <= 10; $i++) { print $i;} TASK-I : Draw nested ordered and unordered lists using for loop. TASK-II: Draw table using for loop.
36

Control Constructs -- foreach


These are similar their counterparts in Perl
foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement

37

Functions
User-defined functions: <?php function hello_world() { print "Hello World"; } hello_world(); ?>
38

Functions (contd.)
<?php /* Passing parameter */ function hello_world($a) { print "Hello World-" . $a; } hello_world(4); ?>

39

Functions (contd.)
In-built / Variable functions:
is_array Finds whether a variable is an array is_bool Finds out whether a variable is a boolean is_double Finds whether a variable is a double is_float Finds whether a variable is a float is_int Find whether a variable is an integer is_integer Find whether a variable is an integer is_long Finds whether a variable is an integer is_null Finds whether a variable is null is_numeric Finds whether a variable is a number or a numeric string
40

Functions (contd.)
is_string Finds whether a variable is a string isset Determine whether a variable is set print_r Prints human-readable information about a variable unset Unset a given variable var_dump Dumps information about a variable

41

Arrays
An array in PHP is a structure which maps keys to values (collection of data) The keys can specified explicitly or they can be omitted If keys are omitted, integers starting with 0 are keys The value mapped to a key can, itself, be an array, so we can have nested arrays
42

Create An Array
A special function is used to specify arrays
array()

Format of Usage
array([key =>] value, )

A key is either a string or a nonnegative integer A value can be anything


43

Create An Array (cont.)


<?php // Single Dimension Array

$a[0]="Zero"; $a[1]="One"; $a[2]="Two"; print $a[1]; for($i=0;$i<count($a);$i++) print $a[$i] . ",";


?>
44

Create An Array (cont.)


<?php $mylist=array("a","b","c","d"); $i=0; while($i<count($mylist)){ print $mylist[$i++] . ","; } ?>

45

Create An Array (cont.)


Multi Dimension Array: <?php $a[0][0]="Value One"; $a[0][1]="Together"; ?>

46

Create An Array (cont.)


Format of array creation
array( [key =>] value, ... )

A hash array
$mothers = array (tom"=>mary", mick"=>ann", bill"=>orla");

Implicit indices are integers, starting at 0


$places = array (Cork, Dublin, Galway);

47

Create An Array (cont.)


If an explicit integer index is followed by implicit indices, they follow on from the highest previous index
Here is an array indexed by integers 1, 2, 3
$places = array (1 => Cork, Dublin, Galway);

Here is an array indexed by integers 1, 5, 6


$places = array (5=> Cork, 1 => Dublin, Galway);
48

Create An Array (cont.)


A two-dimensional hash array
$parents = array ( tom => array (father => bill, mother=> mary), dave => array(father => tom, mother => orla));

A two-dimensional ordinary array


$heights = array (array (10,20),
array(100,200));
49

Array Example 1
<html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris','Ireland'=>'Dublin'); echo 'The capital of Ireland is '; echo $capital['Ireland']; ?> </p> </body> </html>
50

Array Example 1 (cont.)

51

Array Example 2
<html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris', Ireland'=>'Dublin'); echo "The various capitals are\n<ul>"; foreach ($capital as $city) { echo "<li>$city</li>"; }; echo "</ul>" ?> </p> </body> </html>

52

Array Example 2

53

Array Example 3
<html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris', 'Ireland'=>'Dublin'); echo "The various capitals are\n<ul>"; foreach ($capital as $country => $city) { echo "<li>The capital of $country is $city</li>"; }; echo "</ul>" ?> </p> </body> </html>
54

Array Example 3

55

Array Example 4
<html> <head> <title>Details about Fred</title> </head> <body> <h1>Details about Fred</h1> <?php $ages = array ("Fred" => 2, "Tom"=> 45); $parents = array ("Fred" => array("father" => "Tom", "mother"=>"Mary")); print "<p> Fred's age is "; print $ages["Fred"]; print ".</p>"; print "<p>His father is "; print $parents["Fred"]["father"]; print ".</p>"; ?> </body> 56 </html>

Array Example 4

57

Array Functions
array
Create an array

array_change_key_case
Returns an array with all string keys lowercased or uppercased

array_chunk
Split an array into chunks

array_count_values
Counts all the values of an array

array_diff
Computes the difference of arrays
58

Array Functions (cont.)


array_filter
Filters elements of an array using a callback function

array_flip
Flip all the values of an array

array_fill
Fill an array with values

array_intersect
Computes the intersection of arrays

array_key_exists
Checks if the given key or index exists in the array 59

Array Functions (cont.)


array_keys
Return all the keys of an array

array_map
Applies the callback to the elements of the given arrays

array_merge
Merge two or more arrays

array_merge_recursive
Merge two or more arrays recursively

array_multisort
Sort multiple or multi-dimensional arrays
60

Array Functions (cont.)


array_pad
Pad array to the specified length with a value

array_pop
Pop the element off the end of array

array_push
Push one or more elements onto the end of array

array_rand
Pick one or more random entries out of an array

array_reverse
Return an array with elements in reverse order
61

Array Functions (cont.)


array_reduce
Iteratively reduce the array to a single value using a callback function

array_shift
Shift an element off the beginning of array

array_slice
Extract a slice of the array

array_splice
Remove a portion of the array and replace it with something else
62

Array Functions (cont.)


array_sum
Calculate the sum of values in an array.

array_unique
Removes duplicate values from an array

array_unshift
Prepend one or more elements to the beginning of array

array_values
Return all the values of an array

array_walk
Apply a user function to every member of an array 63

Array Functions (cont.)


arsort
Sort an array in reverse order and maintain index association

asort
Sort an array and maintain index association

compact
Create array containing variables and their values

count
Count elements in a variable

current
Return the current element in an array
64

Array Functions (cont.)


each
Return the current key and value pair from an array and advance the array cursor

end
Set the internal pointer of an array to its last element

extract
Import variables into the current symbol table from an array

in_array
Return TRUE if a value exists in an array
65

Array Functions (cont.)


array_search
Searches the array for a given value and returns the corresponding key if successful

key
Fetch a key from an associative array

krsort
Sort an array by key in reverse order

ksort
Sort an array by key

list
Assign variables as if they were an array
66

Array Functions (cont.)


natsort
Sort an array using a "natural order" algorithm

natcasesort
Sort an array using a case insensitive "natural order" algorithm

next
Advance the internal array pointer of an array

pos
Get the current element from an array

prev
Rewind the internal array pointer
67

Array Functions (cont.)


range
Create an array containing a range of elements

reset
Set the internal pointer of an array to its first element

rsort
Sort an array in reverse order

shuffle
Shuffle an array

sizeof
Get the number of elements in variable
68

Array Functions (cont.)


sort
Sort an array

uasort
Sort an array with a user-defined comparison function and maintain index association

uksort
Sort an array by keys using a user-defined comparison function

usort
Sort an array by values using a user-defined comparison function
69

Functions for Strings


addcslashes
Quote string with slashes in a C style

addslashes
Quote string with slashes

bin2hex
Convert binary data into hexadecimal representation

chop
Alias of rtrim()

chr
Return a specific character
70

Functions for Strings (cont.)


chunk_split
Split a string into smaller chunks

convert_cyr_string
Convert from one Cyrillic character set to another

count_chars
Return information about characters used in a string

crc32
Calculates the crc32 polynomial of a string

crypt
One-way string encryption (hashing)
71

Functions for Strings (cont.)


echo
Output one or more strings

explode
Split a string by string

get_html_translation_table
Returns the translation table used by htmlspecialchars() and htmlentities()

get_meta_tags
Extracts all meta tag content attributes from a file and returns an array
72

Functions for Strings (cont.)


hebrev
Convert logical Hebrew text to visual text

hebrevc
Convert logical Hebrew text to visual text with newline conversion

htmlentities
Convert all applicable characters to HTML entities

htmlspecialchars
Convert special characters to HTML entities

implode
Join array elements with a string
73

Functions for Strings (cont.)


join
Join array elements with a string

levenshtein
Calculate Levenshtein distance between two strings

localeconv
Get numeric formatting information

ltrim
Strip whitespace from the beginning of a string
74

Functions for Strings (cont.)


md5
Calculate the md5 hash of a string

md5_file
Calculates the md5 hash of a given filename

metaphone
Calculate the metaphone key of a string

nl2br
Inserts HTML line breaks before all newlines in a string

ord
Return ASCII value of character
75

Functions for Strings (cont.)


parse_str
Parses the string into variables

print
Output a string

printf
Output a formatted string

quoted_printable_decode
Convert a quoted-printable string to an 8 bit string

quotemeta
Quote meta characters
76

Functions for Strings (cont.)


str_rot13
Perform the rot13 transform on a string

rtrim
Strip whitespace from the end of a string

sscanf
Parses input from a string according to a format

setlocale
Set locale information

similar_text
Calculate the similarity between two strings
77

Functions for Strings (cont.)


soundex
Calculate the soundex key of a string

sprintf
Return a formatted string

strncasecmp
Binary safe case-insensitive string comparison of the first n characters

strcasecmp
Binary safe case-insensitive string comparison

strchr
Find the first occurrence of a character
78

Functions for Strings (cont.)


strcmp
Binary safe string comparison

strcoll
Locale based string comparison

strcspn
Find length of initial segment not matching mask

strip_tags
Strip HTML and PHP tags from a string

stripcslashes
Un-quote string quoted with addcslashes()
79

Functions for Strings (cont.)


stripslashes
Un-quote string quoted with addslashes()

stristr
Case-insensitive strstr()

strlen
Get string length

strnatcmp
String comparisons using a "natural order" algorithm
80

Functions for Strings (cont.)


strnatcasecmp
Case insensitive string comparisons using a "natural order" algorithm

strncmp
Binary safe string comparison of the first n characters

str_pad
Pad a string to a certain length with another string

strpos
Find position of first occurrence of a string
81

Functions for Strings (cont.)


strrchr
Find the last occurrence of a character in a string

str_repeat
Repeat a string

strrev
Reverse a string

strrpos
Find position of last occurrence of a char in a string

strspn
Find length of initial segment matching mask
82

Functions for Strings (cont.)


strstr
Find first occurrence of a string

strtok
Tokenize string

strtolower
Make a string lowercase

strtoupper
Make a string uppercase

str_replace
Replace all occurrences of the search string with the replacement string 83

Functions for Strings (cont.)


strtr
Translate certain characters

substr
Return part of a string

substr_count
Count the number of substring occurrences

substr_replace
Replace text within a portion of a string

trim
Strip whitespace from the beginning and end of a string 84

Functions for Strings (cont.)


ucfirst
Make a string's first character uppercase

ucwords
Uppercase the first character of each word in a string

vprintf
Output a formatted string

vsprintf
Return a formatted string
85

Functions for Strings (cont.)


wordwrap
Wraps a string to a given number of characters using a string break character.

nl_langinfo
Query language and locale information

86

Example 1
<?php $str = 'The quick brown fox jumped over the lazy old dog'; $fox = substr($str,16,3); //fox $fox = substr($str,-32,3); //fox $middle = substr($str,20,11); //jumped over $end_char = substr($str,-1); //g ?>
87

Example 2
<?php $array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // lastname,email,phone ?>

88

Example 3
explode(",",$mylist); split(",",$mylist);
<?php $mylist = array("a","b","c","d"); $mylist = explode(",",$mylist); for($i=0; $i<count($mylist); $i++) print $mylist[$i] . "<br>"; ?>
89

Example 4
<?php $string = "Thiss a test"; if(str_replace(" ","",$string) == "Thiis a test") echo str_replace(" ","",$string); ?>

90

Numbers and Math Operations


<?php echo 2 + 3; echo <br>; $a=5; $b=9; echo $a + $b; ?> <?php $a = 1.234; $b = 5; echo bcadd($a, $b); /** 6 **/ echo bcadd($a, $b, 4); // 6.2340 ?>
91

(cont.)
Mathematical Functions
abs Absolute value bindec Binary to decimal cos Cosine ceil Round fractions up floor Round fractions down is_nan Finds whether value is not number max Find highest value min Find lowest value mt_rand Generate a better random value mt_srand Seed the better random number generator rand Generate a random integer round Rounds a float sqrt Square root srand Seed the random number generator
92

Examples
<?php echo rand() . \n; echo rand() . \n; echo rand(5, 15); // random number between 5 - 15 ?> <?php echo round(3.4); // 3 echo round(3.6); // 4 echo round(1.95583, 2); // 1.96 ?>
93

Dates and Times


<?php print date(j/n/Y); print date(y-m-d); ?> <?php print date(Y-m-d H:i:s); ?>

94

format char
a/A d D F g/G h/H I J l L M M N O R S S T U W W Y Y Z Z

Description Lowercase/Uppercase Ante meridiem and Post meridiem Day of the month, 2 digits with leading zeros A textual representation of a day, three letters Full textual representation of a month, such as January or March 12-/24-hour format of an hour without leading zeros 12-/24-hour format of an hour with leading zeros Minutes with leading zeros Day of the month without leading zeros A full textual representation of the day of the week Whether it's a leap year Numeric representation of a month, with leading zeros A short textual representation of a month, three letters Numeric representation of a month, without leading zeros Difference to Greenwich time (GMT) in hours RFC 2822 formatted date Seconds, with leading zeros English ordinal suffix for the day of the month, 2 characters Number of days in the given month Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Numeric representation of the day of the week ISO-8601 week number of year, weeks starting on Monday A full numeric representation of a year, 4 digits A two digit representation of a year The day of the year (starting from 0) Timezone offset in seconds. Offset for timezones west of UTC is negative am or pm 01 to 31

Example returned values AM or PM

Mon through Sun January through December 1 through 12 01 through 12 00 to 59 1 to 31 Sunday through Saturday 1 if it is a leap year, 0 otherwise. 01 through 12 Jan through Dec 1 through 12 Example: +0200 Ex: Thu, 21 Dec 2000 16:01:07 +0200 00 through 59 st, nd, rd or th. Works well with j 28 through 31 See also time() 0 (for Sunday) through 6 (for Saturday) Example: 42 (the 42nd week in the year) Examples: 1999 or 2003 Examples: 99 or 03 0 through 365 -43200 through 43200 0 through 23 00 through 23

95

PHP Includes and SSI


require()
includes and evaluates the specified file

include()
includes and evaluates the specified file

include_once()
included only once

require_once ()
included only once
96

CGI Environment Variables


automatically available; server variables $_SERVER[HTTP_USER_AGENT] $_SERVER[SERVER_NAME] $_SERVER[REQUEST_URI] PHP_SELF $_SERVER[QUERY_STRING] $_SERVER[HTTP_REFERER]
97

Handling HTML Forms with PHP


GLOBAL variables are used - $_POST and $_GET (Superglobals) Example: A simple HTML form <form action="action.php" method="post"> <p>Your name: <input type="text" name="name" /></p> <p>Your age: <input type="text" name="age" /></p> <p><input type="submit" /></p> </form> Example: Printing data from our form (action.php) Hi <?php echo $_POST['name']; ?>. You are <?php echo $_POST['age']; ?> years old. TASK Build an authentication / validation application using forms.
98

Example Form
<html><head><title>Application Form</title></head> <body> <form method="POST" action=response.php"> <p>Your surname: <input type="text" name="surname></p> <p>Your address: <input type="text" name="address></p> <button type="submit">Please send me the brochure.</button> </form> </body></html>

Example Response Generator, response.php


<html><head><title>Thank you</title></head> <body> <h1>Thank you</h1> <p>Thank you,<?php echo $_POST[surname] ?>. We will send our brochure to <?php echo $_POST[address] ?>.</p> </body> </html>

99

Example (cont.)

100

Example (cont.)

101

Example (cont.)

102

TASK

Perform Server-side and Client-side validations


103

Server-side validations
>> Refer lessons earlier on functions (in-built)

Client-side validations
<script type="text/javascript"> <!-function validate() { var N=document.getElementById("username").value; submitOK="true"; if (P.length < 1) { alert("Please fill in the username."); document.getElementById(" username ").focus(); submitOK="false"; return false; } if (submitOK=="false") { return false; } if (confirm(Submit?")==false) { return false; } } // --> </script> 104

AJAX
AJAX stands for Asynchronous JavaScript And XML AJAX is a type of programming made popular in 2005 by Google (with Google Suggest) AJAX is not a new programming language, but a new way to use existing standards With AJAX you can create better, faster, and more user-friendly web applications AJAX is based on JavaScript and HTTP requests With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages
105

index.php
<script type="text/javascript"> var hint=""; function GetXmlHttpObject(handler) { var objXMLHttp=null; if (window.XMLHttpRequest) objXMLHttp=new XMLHttpRequest(); else if (window.ActiveXObject) objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); return objXMLHttp; } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML=""; return; } xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var url="gethint_ajax.php"; url=url + "?query=" + str; url=url + "&sid=" + Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } </script> <form>First Name: <input type="text" id="first_name" onkeyup="showHint(this.value)></form> <p><strong><u>Suggestions</u></strong>: <span id="txtHint" style="color: #0000FF;"></span></p>

106

gethint_ajax.php
<?php $first_names = array("Aakpa", "Arman", "Karma", "Kungang", "Lhaki", "Tshetan", "Tashi", "Tshering"); if (isset($_GET["query"])) { $query = $_GET["query"]; //get the query parameter from URL if (strlen($query) > 0) {//lookup all hints from array if length of query > 0 $hint=""; for($i=0; $i<count($first_names); $i++) { if (strtolower($query) == strtolower(substr($first_names[$i], 0, strlen($query)))) { if ($hint == "") { $hint = $first_names[$i]; } else { $hint = $hint . " , " . $first_names[$i]; } } } } if ($hint == "") { // Set output to "no suggestion" if no hint were found or to the correct values $response = "no suggestion"; } else { $response=$hint; } echo $response; //output the response } ?> N.B. Attached: AJAX Script file

107

Passing Information between pages


HTTP is stateless protocol HTTP does not maintain users state and web developers need to work on with alternative to maintain users sessions and web application must be written to track the user's progress from page to page A common method for solving this problem involves sending and receiving cookies. Other methods include server side sessions, hidden variables (when current page is a form), & URL encoded parameters (such as /index.php?session_id=some_unique_session_code) Parameters can be passed from one page to another by:
1. 2. 3. 4. 5. 6.

Forms Hidden Variables QueryStrings - Hyperlinks File System Cookies Session


108

(contd.) Dealing with Hyperlinks


go.html
<a href="dogo.php?list=computer">GO</a>

dogo.php
<?php echo $_GET["list"]; ?>

109

File Uploads
POST method file uploads index.php
<form enctype="multipart/form-data" action="upload.php" method="post"> Upload this file: <input name="file_name" type="file" /> <input type="submit" value="Send File" /> </form>

upload.php
<?php $uploaddir = '/var/www/uploads/'; $uploadfile = $uploaddir . $_FILES[file_name ']['name']; move_uploaded_file($_FILES[file_name ']['tmp_name'], $uploadfile) ?>
110

HTTP Headers
When a browser requests a Web page, it receives a series of HTTP headers in return The most common example of this will be to redirect the Web browser from the current page to another PHP Header() Function <?php //Redirect browser header("Location: http://www.dit.gov.bt/"); exit; ?> <html><body>......</body></html>
111

Finding out about your PHP Environment


<?php phpinfo(); ?>

112

Filesystem and Directory functions


EXAMPLE 1: Reading a file & printing it out line-by-line <?php $fp = @fopen(sample.txt, r) or die(Cannot open sample.txt); while ($line = @fgets($fp, 1024)) { print $line; } @fclose($fp) or die(Cannot close sample.txt); ?> EXAMPLE 2: Reading file content <?php $file_content = file(sample.txt); // file() - reads entire file into an array foreach($file_content as $line) { print $line; } ?> 113

(contd.)
Writing to file and then reading the content of the file <?php $fp = @fopen(sample.txt, w); if(!$fp) { die(Cannot open file); } fputs($fp, PHP is the base of current web technology.\n); fputs($fp, MySQL is the leight-weight database.\n); @fclose($fp); $fp = @fopen(sample.txt, r); if(!$fp) { die(Cannot open file); } while ($line = @fgets($fp, 1024)) { print $line; } @fclose($fp); @unlink($tmp) or die(Cannot delete file); ?>
114

FileSystem Functions: basename -- Returns filename component of path chgrp -- Changes file group chmod -- Changes file mode chown -- Changes file owner copy -- Copies file delete -- See unlink() or unset() dirname -- Returns directory name component of path disk_free_space -- Returns available space in directory disk_total_space -- Returns the total size of a directory file_exists -- Checks whether a file or directory exists filesize -- Gets file size filetype -- Gets file type is_dir -- Tells whether the filename is a directory is_file -- Tells whether the filename is a regular file is_uploaded_file -- Tells whether the file was uploaded via HTTP POST is_writable -- Tells whether the filename is writable 115 mkdir -- Makes directory

Maintaining Sessions with PHP


Session is the process of preserving variable values across script invocations HTTP is a stateless (connectionless) protocol, meaning that after a user leaves your Web page on your application ends, the computer loses all memory of the transactions that have occurred HTTP has no method for tracking users or retaining variables as a person traverses a site Using a Web scripting language like PHP you can overcome the statelessness of the Web This problem was solved with cookies Cookies are files that are stored on the users computer, and are accessible to the script that sent them Session support in PHP consists of a way to preserve certain data across subsequent accesses
116

Session Usage
page1.php
<?php session_start(); echo 'This is Page 1.'; $_SESSION['favcolor'] = 'green'; ?> <a href="page2.php">page 2</a>

page2.php
<?php session_start(); echo 'This is the variable set in Page 1.'; echo $_SESSION['favcolor]; ?> TASK Write a Hit Counter program using session
117

Cookies
Physical storage in client computer to store pieces of information; can be considered as file, folder Set cookies using the SetCookie() function setcookie() function must appear BEFORE the <html> tag first.php <?php setcookie(phpTestCookie, Test Value); ?> <a href=next.php>Go</a> next.php <?php print $_COOKIE[phpTestCookie]; ?>
118

Sending Emails
The mail() function allows you to send mail <?php mail("receiver@mail.com", "My Subject", "Line 1\nLine 2"); ?>

119

PHP 4 Classes and Objects


Classes are object-oriented programming for PHP A class is a collection of variables and functions working with these variables Object-oriented programming consists of three main vocabulary words: classes, methods, and objects. An object is basically a data structure (also known as an abstract data type), which are encapsulated in a set of routines known as methods. A class is a collection of methods and objects. What's the purpose of classes in PHP? It's the same reason as any other programming language: for large projects, classes provide superior organization and less repetitive code var $_name; //private variable function _display() {} //private function A class is defined using the following syntax: $this: In an object, $this is always reference to the caller object :: Operator (scope resolution operator)
120

Example
<?php class Name { var $first_name; var $last_name; function print_name() { print "Your first name is : $this->first_name,"; print "Your last name is : $this->last_name,"; } } $obj = new Name; // Create new object $obj->first_name='Oliver'; $obj->last_name='Butin'; $obj->print_name($obj->first_name, $obj->last_name); ?>
Constructor: Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. <?php class Auto_Cart extends Cart { function Auto_Cart() { $this->add_item("10", 1); } } ?> N.B. Attached: Class Script files

121

Classes and Objects : Inheritance


You need to create a new class that is derived from an existing class. The extended or derived class can have all the variables & methods of the base class, and you can add or override variables & methods in its definition (known as overriding)
<?php class Pet { //Base Class var $food=array(); var $water; function eat() { foreach($this->food as $snack) { print $snack; } } } class Dog extends Pet { //Derived or Extended Class function set_food() { $this->food = array('Ians','Meat','Alpo'); } } $obj = new Dog; $obj->set_food(); $obj->eat(); ?>

122

PHP 5 Classes and Objects


In PHP 5 there is a new Object Model PHP's handling of objects has been completely rewritten, allowing for better performance and more features
<?php class SimpleClass { public $var = 'a default value'; // member declaration public function displayVar() { // method declaration echo $this->var; }

} ?>

Visibility: Members Visibility and Method Visibility


public $public = 'Public'; protected $protected = 'Protected'; private $private = 'Private'; public function MyPublic() { }
123

Constructors and Destructors


<?php class BaseClass { function __construct() { print "In BaseClass constructor\n"; } function __destruct() { print "Destructor\n"; }

} ?>

Class Abstraction: PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract.
<?php abstract class AbstractClass { abstract protected function getValue(); // Force Extending class to define this method } public function printOut() { print $this->getValue() . "\n"; }

class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1"; } }

124

Patterns
Patterns are ways to describe best practices and good designs They show a flexible solution to common programming problems Factory: The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object.
<?php class Example { public static function factory($type) // The parameterized factory method { if (include_once 'Drivers/' . $type . '.php') { $classname = 'Driver_' . $type; return new $classname; } else { throw new Exception ('Driver not found'); } } } ?> <?php $mysql = Example::factory('MySQL'); // Load a MySQL Driver ?>

Singleton: The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection.
125

SQL (Structured Query Language) Basics MySQL


1. MySQL Login / Connection and User Creation # mysql --user=root mysql # mysql -A --user=username dbname password mysql> GRANT ALL PRIVILEGES ON *.* TO vishanta@localhost IDENTIFIED BY 'password' WITH GRANT OPTION; mysql> GRANT ALL PRIVILEGES ON *.* TO vishanta@"% IDENTIFIED BY 'password' WITH GRANT OPTION; 2. Changing root password mysql> UPDATE mysql.user SET Password=PASSWORD(new_passwd) WHERE user='root'; or mysql> SET PASSWORD FOR root=PASSWORD('new_passwd'); or shell> mysqladmin -u root password new_passwd mysql>FLUSH PRIVILEGES;

mysql> show databases; <show> create database dbase1; <create database> use dbase1; <use> show tables; create table Table1 <create table> (Name varchar(25), Address varchar(30)); drop table Table1; <drop> desc Table1; <desc> insert into Table1 Values ('James', 'USA'); <insert> select * from Table1; <select> update Table1 Set Name='Tashi' where Name='MyName'; <update> alter table Table1 add id tinyint; <alter> delete from Table1 where id=3; <delete> N.B. Attached: MySQL126 File

PHP and MySQL


<?php mysql_connect("mysql_host ", "mysql_user ", "mysql_password"); $result = mysql_db_query("mysql_db", "SELECT * FROM Table1;"); while ($row = mysql_fetch_array($result)) { echo $row["id"]; echo $row["Name"]; echo $row["Address"]; } mysql_free_result($result); ?> Creating Database, Creating Table, Dropping Database, and Dropping Database <?php mysql_connect("", "", "") or die("Could not connect."); mysql_create_db("db"); mysql_db_query("db","CREATE TABLE Employee (EmpID INT, EmpName VARCHAR(25))"); mysql_drop_query("db","DROP TABLE Employee"); mysql_drop_db("db"); ?>
Application Development: Forms, Database, Session, Authentication, Add/Edit/Delete/View operations

127

PostgreSQL
Latest version PostgreSQL 8.3.5
CREATE DATABASE "VishantaDB WITH OWNER = postgres ENCODING = 'UTF8'; CREATE TABLE employee ( emp_id int NOT NULL PRIMARY KEY, emp_name varchar(35) NOT NULL, age int, join_date date ); INSERT INTO employee VALUES(1, 'abc', 21, '2003-03-17'); INSERT INTO employee VALUES(2, 'xyz', 24, '2001-10-02');

N.B. Attached: PostgreSQL 8.3.5, 7.3 File

128

PHP and PostgreSQL


<? $pgconn = pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=passwd"); if (!$pgconn) { print("Connection Failed."); } $result = pg_exec($pgconn, "SELECT version();"); print (pg_result($result, 0, 0)); print ("<br>Number of rows: " . pg_numrows($result) . "<hr>"); $result = pg_exec($pgconn, "SELECT current_date;"); print (pg_result($result, 0, 0)); pg_freeresult($result); pg_close($pgconn); ?>
N.B. Attached: PostgreSQL 8.3.5, 7.3 File 129

PHP and PostgreSQL (contd.)


<? $pgconn = pg_connect("host=localhost port=5432 dbname=VishantaDB user=postgres password=passwd"); if (!$pgconn) { print("Connection Failed."); } $sql = "SELECT * FROM employee ORDER BY emp_id;"; $result = pg_query($pgconn, $sql); while($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) { print ($row["emp_id"] . "\t"); print ($row["emp_name"] . "\t"); print ($row["age"] . "\t"); print ($row["join_date"] . "<br>"); } pg_freeresult($result); pg_close($pgconn); ?>

130

PEAR
Dealing with Database Abstraction with PEAR; PEAR DB PEAR is a framework and distribution system for reusable PHP components PEAR (PHP Extension and Application Repository) is an object-oriented (OO) framework used for the distribution of various classes that can be used freely in your PHP applications One of the most widely used PEAR extensions is DB, the database-independent abstraction layer that provides a common API for use with all of the major database severs, including Oracle, MySQL, PostgreSQL, MS SQL Server 2000 and many more

131

PEAR in MySQL
mysql.php <? require_once("DB.php"); /* Import the PEAR DB interface. */ $hostname = "localhost"; $dbUser = "user"; $dbPass = "passwd"; $dbName = "db"; $dsn = "mysql://$dbUser:$dbPass@$hostname/$dbName"; // connect to the database $db = DB::connect($dsn); if (DB::isError($db)) { die ($db->getMessage()); exit; } $sql = "SELECT * FROM table1"; $result = $db->query($sql); while($row = $result->fetchrow(DB_FETCHMODE_ASSOC)) { echo $row["field1"] . " => " . $row["field2"] . "<br />"; } $result->free(); $db->disconnect(); ?>

132

Captcha
Completely Automated Public Turing test to tell Computers and Humans Apart CAPTCHA: Telling Humans and Computers Apart Automatically A CAPTCHA is a program that can tell whether its user is a human or a computer Uses PHP GD library A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown below, but current computer programs can't:

N.B. Attached: Captcha script


133

CSS
Cascading Style Sheets CSS is a stylesheet language used to describe the presentation of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can be applied to any kind of XML document Styles were added to HTML 4.0 to solve a problem External Style Sheets can save you a lot of work
N.B. Attached: CSS Example
134

Introduction to XML
XML stands for eXtensible Markup Language XML was designed to transport and store data XML is used primarily for data storage and organization XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags XML is designed to be self-descriptive XML is a W3C Recommendation The Extensible Markup Language (XML) is a generalpurpose specification for creating custom markup languages Render XML document with XSLT or CSS
135

XML (contd.)
<?xml version="1.0" encoding="UTF-8" ?> <root> <child> <subchild>.....</subchild> </child> </root> <?xml version="1.0" encoding="ISO-8859-1"?> <library> <book> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book> <title>Learning XML</title> <author>Erik T. Ray</author> <year>2008</year> <price>39.95</price> </book> </ library >

136

PHP and XML


1. XML Expat Parser (attached example) To read and update - create and manipulate - an XML document, you will need an XML parser. The built-in Expat parser makes it possible to process XML documents in PHP. 2. XML DOM (attached example) <?php $xmlDoc = new DOMDocument(); $xmlDoc->load("test.xml"); print $xmlDoc->saveXML(); ?>

137

PHP and XML (contd.)


3. SimpleXML

(attached example)

SimpleXML is new in PHP 5. It is an easy way of getting an element's attributes and text, if you know the XML document's layout. Compared to DOM or the Expat parser, SimpleXML just takes a few lines of code to read text data from an element. <?php $xml = simplexml_load_file("test.xml"); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; } ?>

138

RSS Feeds
Really Simple Syndication (RSS 2.0) Rich Site Summary (RSS 0.91) RSS formats are specified using XML RSS is a family of Web feed formats used to publish frequently updated workssuch as blog entries, news headlines, audio, and videoin a standardized format RSS is a lightweight XML format designed for sharing headlines and other Web content RSS feeds can be read using software called an "RSS reader", "feed reader", or "aggregator", which can be web-based or desktop-based Advantage: RSS solves a problem for people who regularly use the web. It allows you to easily stay informed by retrieving the latest content from the sites you are interested in. You save time by not needing to visit each site individually. You ensure your privacy, by not needing to join each site's email newsletter N.B. Attached: RSS Example
139

Image / Graphics Handling in PHP (Introduction to GD library)


As well as generating dynamic HTML, PHP can generate and manipulate images
<?php $im = ImageCreate(200,200); // Create a new palette based image $blue = ImageColorAllocate($im,0x00,0x00,0xFF); // Allocate color for an image $green = ImageColorAllocate($im,0x00,0xFF,0x00); ImageFilledRectangle($im,50,50,150,150,$green); ImageString($im, 3, 25, 160, 'A Simple Text String', $green); // Draw a string horizontally // imagestring (resource $image, int $font, int $x, int $y, string $string, int $color) ImageLine($im, 60, 60, 120, 120, $blue); // imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) header('Content-Type: image/png'); ImagePNG($im); ImageDestroy($im); ?>
140

PHP Templating with Smarty


Templating Engine for presentation of data PHP Smarty engine is an implementation of PHP Templates PHP Template is a great way of separation of business logic and presentation layers Smarty is a set of PHP classes that compile the templates into PHP scripts Smarty is a template language and a very useful tool for designers and programmers To work with Smarty, you work with template files These files are made up of static content but combined with Smarty mark-up tags All the template files have a .tpl extension. The Smarty template tags are enclosed within { and } delimiters N.B. Attached: Smarty document & example
141

Example
<?php require_once ("./libs/Smarty.class.php"); $smarty = new Smarty; $smarty->assign("Username", "Vishanta Rayamajhi"); $friends = array("Mike", "Simpson", "Bill", "Torvald"); $smarty->assign("friends", $friends); $smarty->display("index.tpl"); ?>
templates/index.tpl <html> <head><title>PHP Smarty</title></head> <body> Hello everyone! This is a Smarty page.<br /> Hello {$Username} <hr><u>Friends List</u>:<br /> {section name=i loop=$friends} {$friends[i]}<br> {/section} </body> </html>

142

PHP Web-Security
Do not have a PUBLICLY accessible phpinfo() file phpinfo() exposes all types of information including server configurations Turn off error reporting in /etc/php.ini file, turn display_errors = On during development, and turn it Off in production Extension Management Keep private files and folders private any file without .php extension will not be parsed as PHP, hence do not put your DB connection file as connection.inc, but put it as connection.inc.php. Also, place these sensitive files outside public directory (below root directory). .htaccess file can be used to protect sensitive directories with a prompt for username/password upon access Use secure connection as far as possible HTTPS (SSL, port 443), encryption of data using SSL services like VeriSign Be careful with Open Source application and revise security If you are acting as a web and system administrator for your web server, then you possible security mechanisms, like DMZ, NAT, Port Concealing, disabling unnecessary ports (telnet <server> 25), DOS attacks, disabling port scanner like nmap
143

PHP Web-Security (contd.)


If you have access and you are web administrator, know you php.ini and httpd.conf very well Let register_globals = Off, with this set to On, variable lets say $news_is is treated same as $_GET[news_id] or $_POST[news_id], and there is chance of your website to be hacked or data to be tampered Limit yourself with Database access use a limited MySQL / PostgreSQL user for applications and only allow yourself what you need to get the job done. For example, do you really need the privilege of DELETE? Always update and make backups and prior to porting to production, have the scripts and functionality (process flows) thoroughly verified in test / development environment, especially while you update or upgrades new features to an already developed and launched application Validation Client-side validation (JS) and Server-side validation Snooping Prevention Have .htaccess authentication wherever applicable to prevent snooping snoop (spy, pry, poke)
144

PHP Web-Security (contd.)


Hashing Password hashing is done in back-end and validation is carried out in PHP application using md5 or sha1 hash function; both hasing usage esp. in Online Banking application with login password and transaction password Usage: md5($_POST[password]) != $dbmemberpassword) in SQL Injection SQL injection is a technique for exploiting Web applications by using client supplied data in SQL queries without first stripping illegal characters. The hacker inputs SQL commands into Web page forms or parameters. The attacker may be able to run any SQL commands on your database that may lead to compromise of the database server. Despite being remarkably simple to protect against, there is an astonishing number of production systems connected to the Internet that are vulnerable to this type of attack. Remedy: Parse and filter all input
145

processlogin.php file for authentication

PHP Web-Security (contd.)


SQL Injection (Remedy)
Use md5 or sha1 for password field ' OR 'x' = 'x is a basic check for SQL Injection mysql_real_escape_string() can also be used around each variable to prevent SQL Injection; adds backslashes to the special characters like quote addslashes & strip_tags functions could be used to make it more secured SELECT * FROM user_table WHERE username = '$user' AND password = '$pass Doing this way makes your application SQL Injection vulnerable

when your application allows users to directly or even inadvertently insert client-side languages such as HTML or JavaScript without any type of encoding. The simplest example would probably be someone submitting the text "</td>" into your forum, guestbook, comments or what have you. If your page is made up of tables, and this text is not encoded (and therefore interpreted by your browser along with the rest of your HTML), your page will now appear broken to anyone who visits. htmlentities() can be used to encode users input wherever required; <b>bold</b> is converted to &lt;b&gt;bold&lt;/b&gt; strip_tags() is the main function used; echo strip_tags(<script>alert(test);</script>); will
output alert(test);
146

Cross-Site Scripting (XSS) Cross-Site Scripting (or XSS) is possible

PHP Web-Security (contd.)


Hidden fields and forms improper posting of data via form Cookie Tampering Cookies your site sends to a visitor's browser contain information about that bisitor. When the browser sends the cookie back, your site uses the information it contains to generate a new page. Don't trust the newtwork. A cookie could be modified or forged by a malicious user, perhaps fooling your site somehow. Solution:

Encrypt Cookie

Query Strings Have register_globals turned on (mentioned earlier) Spoofing Email Headers Take special caution while using PHP in-built mail() function to send emails. The fields need to be properly validated, specially, the email fields. Spammers could inject spam in case email not properly validated (a spoofing attack is a situation in which one person or program successfully masquerades as another by falsifying data and thereby gaining an illegitimate advantage) Captcha Use Captcha images in form registrations Link Traversal this is generally used by hackers to identify URLs that may no longer be in production but are still referenced in commented-out sections of your Web application. The remedy is to analyze the link structure and ensure that any unnecessary links are removed from public access Path Truncation specific to Web Server configuration in which directory browsing is allowed Hidden Web Paths hacker finds hidden paths or references in the source code or comments within a Web application. This information could provide access to restricted areas of your Web application. For example: <!-- my old path /webroot/old/code.php --> This is usually done in beta version and not in production
147

PHP Web-Security (contd.)


Backup and Extension Checking usually refers to having backups being kept in directories (backups/) which might lead to potential security loophole for hackers Parameter Passing and Buffer Overflow hacker evaluates parameters used by scripts and inputs invalid or user-specific values. The passing of variations of parameters (Query Strings) might eventually lead to buffer overflows in application. The remedy is to validate all input from user on server side and not only relying in JavaScript validation Sessions utilization, session hi-jacking, session fixation Session hi-jacking occurs when an attacker is able to take over another person's active session. Depending on how the session ID is generated to begin with, he might be able to brute-force guess it. Some developers un-knowingly create very predictable ID's by using timestamps or an IP address as a basis for generating the session ID; not a good idea. The attacker might also be able to con you into giving them your ID, for example if the ID is passed along in the url and you send him a link to the site, he can now see whatever your session ID allows. You could even reverse the situation where an attacker sends you a link to a site with a pre-existing session ID; if you were to login to the site or transmit any personal information with the attacker's ID, then he would be able to see it. That is referred to as session fixation. Probably the safest way to handle sessions would be to force your visitors to use cookies, and store the session information in a secure database. PHP has a function, session_set_save_handler() for exactly this purpose, and a great benefit is that you don't need to alter any of your existing session code to make it work. You might also consider using session_regenerate_id() to ensure that a fresh ID is created for each new login. Sessions are likely the most valuable aspect to your application, and at the same time, the most vulnerable point of attack 148

PHP Web-Security (contd.)


Filesystem Security only allow limited permissions to files File Uploads Take special care with file uploads (write permission) CSRF (Cross-site request forgery) attacks, Proxy Phishing, Shared hosting these jargons are esp. point of concentration from hosting point of views and not very much related to application developers CRLF Injection CRLF Injection attack occurs when a hacker manages to inject CRLF Commands (\r and \n) into the system. This kind of attack is not a technological security hole in the Operating System or server software, but rather it depends on the way that a website is developed Google Hacking Google hacking comes into picture when a hacker tries to find exploitable targets and sensitive data by using search engines. The Google Hacking Database (GHDB) is a database of queries that identify sensitive data. This needs special Web Vulnerability Scanner. Google hacking is a term that refers to the act of creating complex search engine queries in order to filter through large amounts of search results for information related to computer security. In its malicious format it can be used to detect websites that are vulnerable to numerous exploits and vulnerabilities as well as locate private, sensitive information about others, such as credit card numbers, social security numbers, and passwords
149

PHP Web-Security (contd.)


Cross-Browser Compatibility Keeping Current PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system. Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes

150

Thank you
Er. Vishanta Rayamajhi International ICT Expert +977 98510 21580 vishanta.rayamajhi@gmail.com IM (r_vishanta in Yahoo and MSN)
151

PHP with PostgreSQL 8.3.5 / 7.3.2 Tutorial


Connect to PostgreSQL Server: pgsql_connect.php
<? //$pgconn = pg_pconnect("dbname=mydb");
$pgconn = pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=passwd");

if (!$pgconn) { print("Connection Failed."); } $result = pg_exec($pgconn, "SELECT version();"); print (pg_result($result, 0, 0)); print ("<br>"); print ("Number of rows: " . pg_numrows($result)); print ("<hr>"); $result = pg_exec($pgconn, "SELECT current_date;"); print (pg_result($result, 0, 0)); pg_freeresult($result); pg_close($pgconn); ?> At least with Postgres 7.2, connecting to local postgresql database requires a user in the database with the same name as the user running apache, or the connection fails. Hence: # su postgres postgres$ createuser -d -a -P apache (password=apache) CREATE TABLE employee ( emp_id int NOT NULL PRIMARY KEY, emp_name varchar(35) NOT NULL, age int, join_date date ); INSERT INTO employee VALUES(1, 'abc', 21, '2003-03-17'); INSERT INTO employee VALUES(2, 'xyz', 24, '2001-10-02');

pgsql_query.php
<? $pgconn = pg_pconnect("dbname=mydb"); if (!$pgconn) { print("Connection Failed."); } $sub_query = "(SELECT MAX(emp_id) + 1 FROM employee)"; $sql = "INSERT INTO employee VALUES ($sub_query, '123', 23, '1999-01-01');"; $result = pg_exec($pgconn, $sql) or die("Error in query: $sql. " . pg_last_error($pgconn)); # pg_query can be used above too; no need to include $pgconn in pg_exec & pg_query # pg_errormessage($pgconn) can be used instead of pg_last_error too $sql = "SELECT * FROM employee ORDER BY emp_id;";

$result = pg_query($pgconn, $sql) or die("Error in query: $sql. " . pg_last_error($pgconn)); print ("<table border='1'>"); print ("<tr>"); for ($i=0;$i<pg_num_fields($result);$i++) { print ("<th>" . pg_fieldname($result, $i)); } print ("<tr><th colspan='" . (pg_numfields($result) + 1) . "'>Method-1"); while($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) { #print_r($row); // Uncomment the preceding line to see the entire array. print ("<tr>"); print ("<td>" . $row["emp_id"]); print ("<td>" . $row["emp_name"]); print ("<td>" . $row["age"]); print ("<td>" . $row["join_date"]); } print ("<tr><th colspan='" . (pg_numfields($result) + 1) . "'>Method-2"); for ($i=0;$i<pg_num_rows($result);$i++) { # pg_numrows() also works #$row = pg_fetch_row($result, $i); #for ($i=0;$i<pg_numfields($result);$i++) { # print ("<td>$row[$i]"); #} $row = pg_fetch_object($result, $i); print print print print print } print ("<tr><th colspan='" . (pg_numfields($result) + 1) . "'>Method-3"); for ($row=0;$row<pg_numrows($result);$row++) { print ("<tr>"); for ($col=0;$col<pg_numfields($result);$col++) { print ("<td>" . pg_result($result, $row, $col)); } } print ("</table>"); pg_freeresult($result); pg_close($pgconn); ?> ("<tr>"); ("<td>$row->emp_id"); ("<td>$row->emp_name"); ("<td>$row->age"); ("<td>$row->join_date");

pgsql_pear.php
<? /* Import the PEAR DB interface. */ require_once "DB.php"; /* Database connection parameters. */ $username = ""; $password = ""; $hostname = ""; $dbname = "mydb"; /* Construct the DSN -- Data Source Name. */ $dsn = "pgsql://$username:$password@$hostname/$dbname"; /* Attempt to connect to the database. */ $db = DB::connect($dsn); /* Check for any connection errors. */ if (DB::isError($db)) { die ($db->getMessage()); } /* Execute a selection query. */ $query = "SELECT * FROM employee ORDER BY emp_id;"; $result = $db->query($query); /* Check for any query execution errors. */ if (DB::isError($result)) { die ($result->getMessage()); } print ("<table border='1'>"); print ("<tr><th>Emp ID<th>Emp Name<th>Age<th>Date of Join"); /* Fetch and display the query results. */ while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { print ("<tr>"); print ("<td>" . $row["emp_id"]); print ("<td>" . $row["emp_name"]); print ("<td>" . $row["age"]); print ("<td>" . $row["join_date"]); } /* Disconnect from the database. */ $db->disconnect(); ?>

PostgreSQL 8.3 / 7.3.2 Tutorial


Step -1: Run PostgreSQL server with super-user (root) login
# /etc/rc.d/init.d/postgresql start

Step -2: these as the postgres user:


# su - postgres

Step -3: One option is to create a super-user with something like:


postgres$ createuser -d -a -P vishanta Enter password for user "vishanta": Enter it again: CREATE USER

Step -4: Create Database from user vishanta


$ createdb mydb $ CREATE DATABASE "VishantaDB" WITH OWNER = postgres ENCODING = 'UTF8';

Then do administrative things with that user. I would advise *NOT* using root. If this is a tightly controlled (non-shared) machine, you could make a super user as your normal UNIX login (which hopefully is not root). Ideally you'll only need root to start the postgres service. Step -5: Login into Database from vishanta
$ psql mydb mydb=> (user) mydb=# (database superuser)

PostgreSQL SQL Commands


mydb=> SELECT version(); mydb=> SELECT current_date; $ vi basics.sql CREATE TABLE employee ( emp_id int NOT NULL PRIMARY KEY, emp_name varchar(35) NOT NULL, age int, join_date date ); INSERT INTO employee VALUES(1, 'abc', 21, '2003-03-17'); INSERT INTO employee VALUES(2, 'xyz', 24, '2001-10-02'); mydb=> \i basics.sql

Backup and Restore


postgres$ pg_dump -v -f <filename> <database> (-F c) Location of database: /var/lib/pgsql/data/base/ Unlike Access, there isn't just one file that makes up a database there are a large number of files for each table, index, etc. Backup: // -i = ignore version // -h = server // -p = port // -U = user name // -F c = compress the backup file // -v = verbose messages on dump // -f = file name follows $pg_dump -i -h <server> -p <port> -U <user> -F c -v -f <filename> <DB Name> Restore: // // // // // // // // -i -h -p -U -c -d -C -v = = = = = = = = ignore version server port user name clean install - drop and readd on restore database to restore to when using the -c option create database because it doesn't exist verbose messages

If db DOES NOT exist: $pgrestore -i -h <server> -p <port> -U <user> -v -C -d "template1" <filename> If the db DOES exist: $pgrestore -i -h <server> -p <port> -U <user> -v -c -d <database> <filename>

PHP Smarty
PHP Smarty engine is an implementation of PHP Templates. PHP Template is a great way of separation of business logic and presentation layers. 1. Unpack Smarty file from smarty.php.net (smarty-2.6.14.tar.gz) and as a general case place libs/ directory in your current working directory (say: /var/www/html/smarty/libs/) Important file under libs/ is Smarty.class.php 2. Create directories: - smarty/templates/ to place index.tpl file here - smarty/templates_c/ used by Smarty to create temporary files in real-time - chmod o+w templates_c/ 3. The final directory structure under /var/www/html/smarty/ is: ./libs ./ templates/index.tpl ./ templates_c/ .smarty.php 4. smarty.php
<?php require_once("./libs/Smarty.class.php"); $smarty = new Smarty; $smarty->assign("Username", "Vishanta Rayamajhi"); $smarty->display("index.tpl"); ?>

5. index.tpl
<html> <head> <title>My first Smarty template</title> </head> <body> Hello {$Username} </body> </html>

smarty.php
<?php require_once("./libs/Smarty.class.php"); $smarty = new Smarty; $friends = array("Mike", "Simpson", "Bill", "Torvald"); $smarty->assign("friends", $friends); $smarty->display("index.tpl"); ?>

index.tpl
<html> <head><title>Smarty template with Array display</title></head> <body> Friends List: {section name=i loop=$friends} {$friends[i]}<br> {/section} </body> </html>

PHP-MySQL and Smarty: 1. smarty.php


<?php require "libs/Smarty.class.php"; $smarty = new Smarty; $hostname $dbUser = $dbPass = $dbName = = "localhost"; "user"; "passwd"; "db";

$conn = mysql_connect($hostname, $dbUser, $dbPass); $sqlQry = "SELECT * FROM travel247_reservations"; $result = mysql_db_query($dbName, $sqlQry); $records = array(); while ($row =mysql_fetch_array($result)) { array_push ($records, $row); } // pass the results to the template $smarty->assign("results", $records); // load the template $smarty->display("db.tpl"); ?>

2. index.tpl
<html> <head> <title>PHP Smarty with MySQL Database</title> </head> <body> Here's a table with the results: <br><br> <table cellpadding=1 cellspacing=0 border=0 width=100%> {section name=i loop=$results} <tr {if $smarty.section.i.iteration is odd} bgcolor="#efefef"{/if}> <td>{$results[i].0} <td>{$results[i].1} <td>{$results[i].2} <td>{$results[i].3} <td>{$results[i].4} <td>{$results[i].5} </tr> {sectionelse} <tr><td align="center"><br><b>no product </b> <br> </td></tr> {/section} </table>

PHP Templating with Smarty Intended Audience


This article is intended for PHP programmers and HTML designers interested in applying a new technique for web development PHP templating. Advanced knowledge of PHP programming and HTML is assumed.

Smarty Overview
The theoretical web development process is that: first the designer makes the interface, and breaks it down into HTML pieces for the programmer then the programmer implements the PHP business logic into the HTML. Thats fine in theory, but in practice, from experience, the client frequently comes with more requirements or maybe more modifications to the design or to the business logic. When this happens, the HTML is modified (or words rebuilt) programmer changes the code inside HTML. The problem with this scenario is that the programmer needs to be on stand-by until the designer completes the layout and the HTML files. Another problem is that if there is a major design change then the programmer will change the code to fit in the new page. And thats why I recommend Smarty. Smarty is a templating engine for PHP. You can download it from http://www.phpinsider.com/php/code/Smarty/ or http://smarty.php.net . The installation process is very simple. Just read the documentation and follow up the instructions. So what is Smarty? Smarty is a set of PHP classes that compile the templates into PHP scripts. Smarty is a template language and a very useful tool for designers and programmers.

Smarty for Designers


Designers work with HTML files. To work with Smarty, you work with template files. These files are are made up of static content but combined with Smarty mark-up tags. All the template files have a .tpl extension. The Smarty template tags are enclosed within { and } delimiters. Lets consider the basic structure of a web page. There is a header, a middle part, and a footer. A template file that includes the header and the footer looks like this:
{include file="header.tpl"} <form name="form1"> Label1 <input type="text" name="text1"> <input type="submit" value="submit"> </form> {include file="footer.tpl"}

All the templates should reside in a single template directory. After calling a template for the first time, the compiled template will reside in templates_c.

Smarty language is very poweful. All the variables that come from PHP are identified in Smarty with {$Variable_Name} (we precede them with a $ sign). So if we have a variable in PHP that is called $MyName, then to print it in Smarty you have to write something like:
<html> <body> Welcome, {$MyName} <br> </body> </html>

The power of Smarty lies also in its flexibility. You can insert IFs and LOOPs into the template. The syntax for IF is:
{if <condition> } html code {else} html code {/if}

Lets say you have a dynamic menu based on links. Depending on the link you click, you go to a specific page. So you get from PHP a variable $Menu with a integer value, depending on the page you are. The template looks like :
{if ($Menu == 1) } Option 1 {else} <a href="option1.php">Option 1</a> {/if} {if ($Menu == 2)} Option 2 {else} <a href="option2.php">Option 2</a> {/if}

For coding a loop lets suppose you get an array like the following from PHP :
<table> <tr {section name=user loop=$userID} {if $smarty.section.user.iteration is odd} bgcolor=#efefef {else} bgcolor=#ffffff {/if} > <td> ID = {$userID[user]} </td> <td> Name = {$name[user]} </td> <td> Address = {$address[user]} </td> </tr> {sectionelse} <tr> <td> There is no user. </td> </tr> </section> </table>

Iteration is an internal counter for Smarty. It helps us to know the current iteration of the section. I use this internal variable to make alternate row colors in the table by checking if current iteration value is odd or not (Note that iteration was added to Smarty from version 1.4.4). An alternative for LOOPS is FOREACH which is used to loop over a single associative array.
<foreach from=$users item=current_user> Name = {$current_user} <foreachelse} No user available. </foreach>

The main difference between SECTION and FOREACH is that for SECTION you can start from a specific value, and can also set a step for the iteration, whereas for FOREACH you have to loop over all values.

Smarty for Programmers


The advantage for programmers is that they write the code in a PHP file without having to mix the instructions with HTML. Furthermore, if the designer changes the layout of a page the programmer doesnt have to change the code to suit the new layout since the functionalities wont change. You do your work in your files, assign to the templates all the values needed to print on the site and go out for a beer. You wont get phone calls asking you to change a bit of code because the designer changed the layout and now a set of internal errors cropped up. In the PHP file you need to include the Smarty class require Smarty.class.php'. After that you need to instantiate the smarty with $smarty = new Smarty. To assign a variable to the template you need to $smarty->assign('UserName', John Doe). After everything is finished you call the method to display the template $smarty->display('index.tpl'). A sample code looks like this (index.php) :
<?php require 'Smarty.class.php'; $smarty = new Smarty; $smarty->assign('Username', 'John Doe'); $smarty->display('index.tpl'); ?>

The template (index.tpl) looks like this:


<html> <body> Welcome {$Username} </body> </html>

You can also create an array in PHP an pass it to the template:


$tmp = array ( 'UID'=> '10', &'Name' => 'John Doe', 'Address'=>'Home address'); $smarty->assign('info', $tmp);

Sample Script
This script connects to a local database and select all the products from the Products table. Then it passes all the values to the template, which prints them on the screen. INDEX.PHP
<?php require 'Smarty.class.php'; $smarty = new Smarty; $hostname = "localhost"; $dbUser = "sqluser"; $dbPass = "sqlpass"; $dbName = "sqldb"; // connect to the database $conn = mysql_connect($hostname, $dbUser, $dbPass) or die("Cannot connect to the database"); mysql_select_db($dbName); $sql = "SELECT prodID, info FROM products ORDER BY prodID ASC"; // get all the products from the table $res = mysql_query($sql); $results = array(); $i=0; while ($r=mysql_fetch_array($res)) { $tmp = array( 'prodID' => $r['prodID'], 'info'=> $r['info'] ); $results[$i++] = $tmp; } // pass the results to the template $smarty->assign('results', $results); // load the template $smarty->display('index.tpl'); ?>

INDEX.TPL
<html> <body> Here's a table with the results: <br> <table cellpadding=1 cellspacing=0 border=0 width=100%> {section name=nr loop=$results} <tr {if $smarty.section.nr.iteration is odd} bgcolor="#efefef"{/if}> <td class=fb width=15%> <nobr><a href=&#8221;show-product.php?id={$results[nr].prodID}">Press here</a>

<td class=fb width=29%><a href="show.php?id={$results[nr].prodID}" {popup inarray=$smarty.section.nr.iteration} >{$results[nr].info}</a></td> </tr> {sectionelse} <tr><td align="center"><br><b>no product </b> <br> </td></tr> {/section} </table> <br> Here's a select with the results: <br> <select name="mys"> {section name=nr loop=$results} <option value="{$results[nr].prodID}">{$results[nr].info}</option> {/section} </select> </body> </html>

Summary
Smarty is a great tool for both designers and developers. By using Smarty you can reduce the site development and maintenance times. If you are a developer you no longer need to mix PHP code with HTML code. Just take care of business logic and leave the HTML to the designer.

Other Uses for Smarty


Sending plaintext and HTML emails
There are many situations where PHP is used to send emails. Probably the most common cases are for member signup type applications, where an email is sent to a user when they sign up on your site. Typically these kinds of sites also have a fetch password type email, which sends a password reminder or reset link to a user. Smarty is suited perfectly to managing the templates used in these emails. Frequently I see in peoples code a quickly rushed email template hard coded into their PHP code. This is really hard to manage and clutters up the PHP code. To implement this in Smarty, firstly, you create your email template. The way I do is to code the email subject as the first line of the template. This comes down to personal preference, but doing so allows you to dynamically place content easily in the subject line.

Highlight: Smarty Template


{$user.firstname}, your XYZ Site registration Dear {$user.firstname}, Thank you for signing up at XYZ Site. Your login details are below. Username: {$user.username} Password: {$user.password} Sincerely, Mr. Fake Person XYZ Site Administrator

Remember here that the first line is the subject line. For the example below, lets assume the template is stored in a file called registration-email.tpl. Now its just a matter of running this template through Smarty, and then sending the output through the PHP mail() function.

Highlight: PHP
<?php define('SITE_FROM_EMAIL', 'webmaster@example.com'); function sendRegistrationEmail($user) { require_once('Smarty.class.php'); $smarty = new Smarty(); //$smarty->template_dir = [path to templates] //$smarty->compile_dir = [path to template compile dir] // assign the user's details to the template $smarty->assign('user', $user); // fetch the email body $body = $smarty->fetch('registration-email.tpl'); // the subject is on the first line, so parse that out $lines = explode("\n", $body); $subject = trim(array_shift($lines)); $body = join("\n", $lines); // finally, send the email return mail($user['email'], $subject, $body, 'From: ' . SITE_FROM_EMAIL); } ?>

You will still need to manually customize Smartys template_dir and compile_dir as you would normally with Smarty. Note here that the fetch method returns the template out as a string, rather than outputting is directly as the display method does. Now, to make use of this function, you would use something like:

Highlight: PHP
<?php $user = array('firstname' 'lastname' 'email' 'username' 'password' => => => => => 'Joe', 'Bloggs', 'bloggs@example.com', 'jbloggs', 'jb123');

if (sendRegistrationEmail($user)) echo 'Success'; else echo 'Failure'; ?>

The same principles apply for sending HTML emails also. The biggest difference is that youd probably want to use something like PEARs Mail_Mime class to deal with sending HTML emails. In this case, youd create a template that consisted of HTML code like you would normally with Smarty, then set the output from this as the HTML body.

Ajax
//index.php <script type="text/javascript"> <!-var hint=""; function GetXmlHttpObject(handler) { var objXMLHttp=null; if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); } return objXMLHttp; } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } } function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML=""; return; } xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var url="gethint_ajax.php"; url=url + "?query=" + str; url=url + "&sid=" + Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } //--> </script> <form> First Name: <input type="text" id="first_name" onkeyup="showHint(this.value)"> </form> <br> <p><strong><u>Suggestions</u></strong>: <span id="txtHint" style="color: #0000FF;"></span></p> //gethint_ajax.php <?php $first_names = array("Aakpa", "Arman", "Arati", "Karma", "Kungang", "Lhaki", "Tshetan", "Tashi", "Tshering");; if (isset($_GET["query"])) { $query = $_GET["query"]; //get the query parameter from URL //lookup all hints from array if length of query > 0 if (strlen($query) > 0) { $hint=""; for($i=0; $i<count($first_names); $i++) { if (strtolower($query) == strtolower(substr($first_names[$i], 0, strlen($query)))) { if ($hint == "") { $hint = $first_names[$i];

} else { $hint = $hint . " , " . $first_names[$i]; } } } } // Set output to "no suggestion" if no hint were found or to the correct values if ($hint == "") { $response = "no suggestion"; } else { $response=$hint; } //output the response echo $response; } ?>

Classes and Objects


<?php class Name { var $property1; var $property2; function print_name($first_name, $last_name) { print "Your first name is : $first_name,"; print "Your last name is : $last_name,"; } } // Create new object $obj = new Name; $obj->first_name='Oliver'; $obj->last_name='Butin'; $obj->print_name($obj->first_name,$obj->last_name); ?>

Inheritance

<?php class Pet { //Base Class var $food=array(); var $water; function eat() { foreach($this->food as $snack){ print $snack; } } } class Dog extends Pet { //Derived or Extended Class function set_food() { $this->food = array('Ians','Meat','Alpo'); } } // Create an instance of class = object $obj = new Dog; $obj->set_food();

$obj->eat(); ?>

Example 1:
//class.php <?php class user { var $_userid; // private variable var $username; var $password; var $address; var $phone; var $email; var $age; var $dob; var $description; var $role; function display_user($_userid) { print $this->_userid; print $this->username; print $this->password; print "<hr>"; print "<table border='1' style='font-family: Verdana; font-size: 11px; border-collapse: collapse;'>"; foreach ($this as $key => $val){ print "<tr align='left'>"; print "<th>$key"; print "<td>$val"; } print "</table>"; } } ?> //user.php <?php require_once ("class.php"); $obj = new user; $obj->_userid = 1; $obj->username = "vishanta"; $obj->password = "mypasswd"; $obj->address = "KTM"; $obj->phone = "977-9851021580"; $obj->email = "vishanta.rayamajhi@gmail.com"; $obj->age = 28; $obj->dob = "1978-10-15"; $obj->description = "International ICT Expert"; $obj->role = 1; $obj->display_user($obj->_userid); $obj->_userid = 2; $obj->username = "test"; $obj->password = "password"; $obj->address = "-"; $obj->phone = "457896"; $obj->email = "test@gmail.com"; $obj->age = 35; $obj->dob = "..."; $obj->description = "desc"; $obj->role = 3;

$obj->display_user($obj->_userid); ?>

Example 2
//example.class.php <? class Example { //class-wide variables var $var1; var $var2; //function to gather two numbers function set_numbers($number1, $number2) { $this->var1 = $number1; $this->var2 = $number2; } //function to add numbers together function add_numbers() { return ($this->var1 + $this->var2); } } ?> //exampleuse.php <? require_once("example.class.php"); //create an object variable for the instance of the example object $exampleobject = new Example; $exampleobject->set_numbers(1,3); echo($exampleobject->add_numbers()); //the output will be: 4 ?>

Examples on php and postgreSQL:


//pgsql_connect.php <? //$pgconn = pg_pconnect("dbname=mydb"); $pgconn = pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=passwd"); if (!$pgconn) { print("Connection Failed."); } $result = pg_exec($pgconn, "SELECT version();"); print (pg_result($result, 0, 0)); print ("<br>"); print ("Number of rows: " . pg_numrows($result)); print ("<hr>"); $result = pg_exec($pgconn, "SELECT current_date;"); print (pg_result($result, 0, 0)); pg_freeresult($result); pg_close($pgconn); ?> //pgsql_query.php <? $pgconn = pg_connect("host=localhost port=5432 dbname=VishantaDB user=postgres password=passwd"); if (!$pgconn) {

print("Connection Failed."); } $sql = "INSERT INTO employee VALUES ((SELECT MAX(emp_id) + 1 FROM employee), '123', 23, '1999-0101');"; $result = pg_exec($pgconn, $sql) or die("Error in query: $sql. " . pg_last_error($pgconn)); # pg_query can be used above too; no need to include $pgconn in pg_exec() & pg_query() # pg_errormessage($pgconn) can be used instead of pg_last_error too $sql = "SELECT * FROM employee ORDER BY emp_id;"; $result = pg_query($pgconn, $sql) or die("Error in query: $sql. " . pg_last_error($pgconn)); print ("<table align='center' width='50%' border='1' cellpadding='2' cellspacing='2' style='bordercollapse: collapse; font-family: Verdana; font-size: 11px; color: #555555;'>"); print ("<tr>"); for ($i=0;$i<pg_num_fields($result);$i++) { print ("<th>" . pg_fieldname($result, $i)); } print ("<tr><th colspan='" . (pg_numfields($result) + 1) . "'>Method-1"); while($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) { #print_r($row); // Uncomment the preceding line to see the entire array. print ("<tr>"); print ("<td>" . $row["emp_id"]); print ("<td>" . $row["emp_name"]); print ("<td>" . $row["age"]); print ("<td>" . $row["join_date"]); } print ("<tr><th colspan='" . (pg_numfields($result) + 1) . "'>Method-2"); for ($i=0;$i<pg_num_rows($result);$i++) { # pg_numrows() also works #$row = pg_fetch_row($result, $i); #for ($i=0;$i<pg_numfields($result);$i++) { # print ("<td>$row[$i]"); #} $row = pg_fetch_object($result, $i); print print print print print } print ("<tr><th colspan='" . (pg_numfields($result) + 1) . "'>Method-3"); for ($row=0;$row<pg_numrows($result);$row++) { print ("<tr>"); for ($col=0;$col<pg_numfields($result);$col++) { print ("<td>" . pg_result($result, $row, $col)); } } print ("</table>"); pg_freeresult($result); pg_close($pgconn); ?> //pgsql_pear.php <? /* Import the PEAR DB interface. */ require_once "DB.php"; /* Database connection parameters. */ $username = "postgres"; ("<tr>"); ("<td>$row->emp_id"); ("<td>$row->emp_name"); ("<td>$row->age"); ("<td>$row->join_date");

$password = "passwd"; $hostname = "localhost"; $dbname = "VishantaDB"; /* Construct the DSN -- Data Source Name. */ $dsn = "pgsql://$username:$password@$hostname/$dbname"; /* Attempt to connect to the database. */ $db = DB::connect($dsn); /* Check for any connection errors. */ if (DB::isError($db)) { die ($db->getMessage()); } /* Execute a selection query. */ $query = "SELECT * FROM employee ORDER BY emp_id;"; $result = $db->query($query); /* Check for any query execution errors. */ if (DB::isError($result)) { die ($result->getMessage()); } print ("<table align='center' width='50%' border='1' cellpadding='2' cellspacing='2' style='bordercollapse: collapse; font-family: Verdana; font-size: 11px; color: #555555;'>"); print ("<tr><th>Emp ID<th>Emp Name<th>Age<th>Date of Join"); /* Fetch and display the query results. */ while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { print ("<tr>"); print ("<td>" . $row["emp_id"]); print ("<td>" . $row["emp_name"]); print ("<td>" . $row["age"]); print ("<td>" . $row["join_date"]); } /* Disconnect from the database. */ $db->disconnect(); ?>

Captcha
//index.php <?php session_start(); include('captchaCheck.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Web forms, mail forms with captcha, captcha form example </title> <meta name="description" content="using captcha in web forms, mail forms " /> <meta name="keywords" content=" Web forms, mail forms, using captcha, Form example, with captcha, captcha form, spammers bot, graphically generated code, validation page, examples of captcha, captcha protected page, form without captcha, captcha knowledge, tested form, insertion of captcha generated image, preventing bots, captcha protected form, php, javascript code, How to protect, how to implement captcha in web forms " /> <style type="text/css" media="all"> /* <![CDATA[ */ body{font-family:Verdana, Arial, Helvetica, sans-serif;font-size:.9em} h2{text-align:center;color:#369} .content{width:600px;margin:15px auto;padding:2px;border:1px solid #000;text-align:left;backgroundcolor:#ccc} .cpt{text-align:center} .cpt img{margin:2px 15px 2px 2px;vertical-align:middle} .inp{margin:10px} div.row{clear:both;margin:0;padding:3px 0}

div.row label{float:left;width:150px;padding:0 10px 0 0;text-align:right} div.row label:hover{background-color:#666;color:#fff} #scratch_submit{padding:2px 20px} .error{text-align:center;color:#f00} /* ]]> */ </style> <script type="text/javascript"> function resetta() { var obj=document.getElementById('captchaForm'); var n=obj.elements.length; for(var i=0;i<n;i++){if(obj.elements[i].type == "text" || obj.elements[i].type == 'textarea'){obj.elements[i].value = ''}}; return false; } </script> </head> <body <?php if(isset($error) && $error==1){echo 'onload="document.forms[0].scratch_submit.focus()"';} ?>> <h2>Please insert the requested information below and you may win <br />TEN MILLION DOLLARS</h2> <div class="content"> <form id="captchaForm" name="captchaForm" method="post" action=""> <div class="row"><label for="company">Company: </label><input name="company" type="text" id="company" size="60" value="<?php if(isset($_POST['company'])){echo $_POST['company'];} ?>" /></div> <div class="row"><label for="name">Name: </label><input name="name" type="text" id="name" size="30" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>" /> </div> <div class="row"><label for="name">Surname: </label><input name="surname" type="text" id="surname" size="30" value="<?php if(isset($_POST['surname'])){echo $_POST['surname'];} ?>" /></div> <div class="row"><label for="address">Address: </label><input name="address" type="text" id="address" size="60" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" /></div> <div class="row"><label for="zip">ZIP: </label><input name="zip" type="text" id="zip" size="8" value="<?php if(isset($_POST['zip'])){echo $_POST['zip'];} ?>" /> City: <input name="city" type="text" id="city" size="20" value="<?php if(isset($_POST['city'])){echo $_POST['city'];} ?>" /> Region: <input name="region" type="text" id="region" size="5" value="<?php if(isset($_POST['region'])){echo $_POST['region'];} ?>" /></div> <div class="row"><label for="email">Email: </label><input type="text" name="email" size="40" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" /></div> <div class="row"><label for="telephone">Telephone: </label><input name="telephone" type="text" id="telephone" size="20" value="<?php if(isset($_POST['telephone'])){echo $_POST['telephone'];} ?>" /> Mobile: <input name="mobile" type="text" id="mobile" size="20" value="<?php if(isset($_POST['mobile'])){echo $_POST['mobile'];} ?>" /></div> <div class="row"><label for="comments">Comments: </label><textarea name="comments" cols="45" rows="5" id="comments"><?php if(isset($_POST['comments'])){echo $_POST['comments'];} ?></textarea></div> <div class="clear">&nbsp;</div> <hr /> <p>Ready ? Ok, but before you click 'Send Form' please insert the same letters and numbers you see in this image into the box to your bottom</p> <div class="cpt"><img src="captchaImage.php" alt="captcha image"/><input type="text" id="captcha_input" name="captcha_input" size="15" /></div> <hr /> <?php if($error == 1){ ?><p class="error">The code you inserted was not correct. Try with the new code above</p><?php } ?> <div class="inp" style="text-align:center"><label for="submit">&nbsp;</label><input type="submit" name="scratch_submit" id="scratch_submit" value="Send Form" /></div> </form> </div> </body> </html> //captchaCheck.php <? $error=0; if(isset($_POST['scratch_submit'])&& isset($_SESSION['pass'])){ if(isset($_POST['captcha_input'])){ if($_SESSION['pass']==$_POST['captcha_input']){ $_SESSION['post']=$_POST; header("Location: result.php"); exit; } else {$error=1;}

} else {$error=1;} } ?> //captchaImage.php <? session_start(); header("Content-Type: image/png"); // custom parameters $box_w $box_h $font $font_size $font_angle $font_x $font_y $color_background $color_text red $color_lines red $thickness $lines_angle $lines_number

// or image/jpg

125; 35; 'arial.ttf'; // 24; = 0; // = 10; = 5; = 'black'; // = 'white'; // = 'white'; = 1; = 5; = 5;

= = = =

// Width of the captha box // Height of the captha box Used font // Size of the font Angle of text // Margin left // Margin top Bakground color: black, white, green, blu, red Text color: black, white, green, black, white, green,

blu, blu,

// Lines color:

// Thickness of lines // angle of lines (from 1 to 10) // numbers of lines

// set a passcode $pass = ''; $nchar = 5; // number of characters in image for($i=1;$i<=$nchar;$i++){ $charOnumber = rand(1,2); if($charOnumber == 1){ $chars = 'ABEFHKMNRVWX'; // custom used characters $n = strlen($chars)-1; $x = rand(1,$n); $char = substr($chars,$x,1); $pass .= $char; } else { //$number = rand(3,7); $numbers = array(1,2,3,4,7); // custom used numbers $n = count($numbers)-1; $number = $numbers[rand(1,$n)]; $pass .= $number; } } // set the session $_SESSION["pass"] = $pass; // create the image resource $image = ImageCreatetruecolor($box_w,$box_h); // set $white $black $green $red $blu colors = ImageColorAllocate($image, = ImageColorAllocate($image, = ImageColorAllocate($image, = ImageColorAllocate($image, = ImageColorAllocate($image,

255, 255, 255); 0, 0, 0); 0, 255, 0); 255, 0, 0); 0, 0, 255);

switch($color_background){ case 'black': $color_background = $black; break; case 'white': $color_background = $white; break; case 'green': $color_background = $green; break; case 'blu':

$color_background = $blu; break; case 'red': $color_background = $red; break; default: $color_background = $black; } switch($color_text){ case 'black': $color_text = $black; break; case 'white': $color_text = $white; break; case 'green': $color_text = $green; break; case 'blu': $color_text = $blu; break; case 'red': $color_text = $red; break; default: $color_text = $black; } switch($color_lines){ case 'black': $color_lines = $black; break; case 'white': $color_lines = $white; break; case 'green': $color_lines = $green; break; case 'blu': $color_lines = $blu; break; case 'red': $color_lines = $red; break; default: $color_lines = $white; } // set background imagefill($image, 0, 0, $color_background); // set text imagettftext($image, $pass);

$font_size,

$font_angle,

$font_x,

$font_size

$font_y,

$color_text,

$font,

// set lines imagesetthickness($image,$thickness); $step = $box_w/$lines_number; switch($lines_angle){ case 1: $start = 5; $end = 5; break; case 2: $start = 5; $end = 10; break; case 3: $start = 5; $end = 15;

break; case 4: $start = $end = break; case 5: $start = $end = break; case 6: $start = $end = break; case 7: $start = $end = break; case 8: $start = $end = break; case 9: $start = $end = break; case 10: $start = $end = break; } $a = $start; $b = $end;

5; 20;

5; 25;

5; 30;

5; 35;

5; 40;

5; 45;

5; 50;

for($i=1;$i<=$lines_number;$i++){ $l = $start; $l1 = $end; imageline($image, $l, 1, $l1, $box_h, $color_lines); $start = $a + ($step*$i-1); $end = $start + $b; } // created image imagejpeg($image); imagedestroy($image); ?> //result.php <? session_start(); if(isset($_SESSION['post'])){$post = $_SESSION['post'];}else{$post=NULL;} if(isset($post['company'])){$_company = $post['company'];}else{$_company = '';} if(isset($post['name'])){$_name = $post['name'];}else{$_name = '';} if(isset($post['surname'])){$_surname = $post['surname'];}else{$_surname = '';} if(isset($post['address'])){$_address = $post['address'];}else{$_address = '';} if(isset($post['zip'])){$_zip = $post['zip'];}else{$_zip = '';} if(isset($post['city'])){$_city = $post['city'];}else{$_city = '';} if(isset($post['email'])){$_email = $post['email'];}else{$_email = '';} if(isset($post['telephone'])){$_telephone = $post['telephone'];}else{$_telephone = '';} if(isset($post['mobile'])){$_mobile = $post['mobile'];}else{$_mobile = '';} if(isset($post['comments'])){$_comments = $post['comments'];}else{$_comments = '';} echo echo echo echo echo echo echo "Ok! You have inserted the correct captcha code. <br><br>"; "You information has been sent <br><br>"; "This is what you sent <br><br>"; "Your Company: \"" . $_company . "\" <br>"; "Your Name: \"" . $_name . "\" <br>"; "Your Surname: \"" . $_surname . "\" <br>"; "Your Address: \"" . $_address . "\" <br>";

echo echo echo echo echo echo

"Your "Your "Your "Your "Your "Your

Zip: \"" . $_zip . "\" <br>"; City: \"" . $_city . "\" <br>"; email: \"" . $_email . "\" <br>"; Telephone: \"" . $_telephone . "\" <br>"; Mobile: \"" . $_mobile . "\" <br>"; Comments: \"" . $_comments . "\" <br>";

echo 'Thank you '; // send form content to an email address $mailuser = "vishanta.rayamajhi@gmail.com"; // insert destination email address here $header = "Return-Path: ".$mailuser."\r\n"; $header .= "From: form with captcha <".$mailuser.">\r\n"; $header .= "Content-Type: text/html;"; $mail_body = ' The User: '. $_company .' has sent his input. Your Name: '. $_name . '<br> Your Surname: '. $_surname . '<br> Your Address: '. $_address . '<br> Your Zip: '. $_zip . '<br> Your City: '. $_city . '<br> Your email: '. $_email . '<br> Your Telephone: '. $_telephone . '<br> Your Mobile: '. $_mobile . '<br> Your Comments: '. $_comments . '<br>' ; mail ($mailuser, 'Form sent', $mail_body, $header); ?>

CSS- CASCADING STYLE SHEET


//css.htm <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>CSS Example</title> <style> a {color: #FF0000; text-decoration: none;} a:hover {color: GREEN; text-decoration: underline; font-weight: bold;} .Title { font-weight: bold; font-size: 11px; color: #FFFFFF; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; background-color: #333366; } .Field { font-size: 11px; color: black; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; background-color: #CCCCCC; } .Box { font-size: 11px; color: #336699; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica;

border: 1px solid #000080; padding-left: 4px; padding-right: 4px; padding-top: 1px; paddingbottom: 1px; background-color: #E5F4FB; } .Table { font-size: 11px; color: #000080; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; background-color: #EEF3FB; } .TableHigh { font-size: 11px; color: #000080; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; background-color: #B6C7E5; } .Elaborate { font-weight: normal; font-size: 11px; color: #FFFFFF; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; background-color: #336699; } .Data { font-size: 11px; color: black; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; background-color: #EFEFEF; } .ButtonPrev { border-style: solid; border-width: 1px; padding: 0px; font-family: Verdana; font-size: 11px; font-weight: bold; color: #000080; } .Button { font-size: 11px; color: #336699; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; border: 1px solid #000080; padding-left: 4px; padding-right: 4px; padding-top: 1px; paddingbottom: 1px; background-color: #E5F4FB; font-weight: bold; } .Text { font-size: 11px; color: #336699; font-family: Verdana, Tahoma, Trebuchet MS, Arial, Helvetica; } </style> </head> <body>

<table cellSpacing="2" cellPadding="2" border="0" align="center" width="700"> <tr class="Elaborate"> <th>SN</th> <th>Date</th> <th>Property</th> <th>Client</th> <th>Date From</th> <th>To Date</th> </tr> <tr class='Table'> <td align='center' style='font-weight: bold;'>1</td> <td>2007-10-02</td> <td><a href="#">ACAPULCO, CALLE MARQUES</a></td> <td>John Smith</td> <td>2007-10-17</td> <td>2007-10-19</td> </tr> <tr class='Table'> <td align='center' style='font-weight: bold;'>2</td> <td>2007-10-05</td> <td><a href="#">PLAYA Y GOLF RESIDENCIAL</a></td> <td>Gary Sobers</td> <td>2007-11-26</td> <td>2007-12-03</td> </tr> </table> </body> </html>

XML- EXTENSIBLE MARKUP LANGUAGE


//test.xml <?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>DIT</to> <from>Vishanta Rayamajhi</from> <heading>PHP-XML Training</heading> <body>Extensive and practical training ongoing...</body> </note>

Examples:
//Expat-parser.php <? $parser = xml_parser_create(); function start($parser, $element_name, $element_attrs) { switch($element_name) { case "NOTE": echo "-- Note --<br />"; break; case "TO": echo "To: "; break; case "FROM": echo "From: "; break; case "HEADING": echo "Heading: "; break; case "BODY": echo "Message: "; } }

function stop($parser, $element_name) { echo "<br />"; } function char($parser, $data) { echo $data; } xml_set_element_handler($parser, "start", "stop"); xml_set_character_data_handler($parser, "char"); #$fp = fopen("test.xml", "r"); #while ($data = fread($fp,4096)) { # xml_parse($parser, $data, feof($fp)) or die (sprintf("XML Error: %s at xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); #} $xml_document = file("test.xml"); foreach ($xml_document as $line) { xml_parse($parser, $line); } xml_parser_free($parser); ?>

line

%d",

//XML-DOM.php <?php $xmlDoc = new DOMDocument(); $xmlDoc->load("test.xml"); print $xmlDoc->saveXML(); ?> <hr> <h3>Looping through XML</h3> We want to initialize the XML parser, load the XML, and loop through all elements of the <note> element: Example: <br><br> <?php $xmlDoc = new DOMDocument(); $xmlDoc->load("test.xml"); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) { print $item->nodeName . " = " . $item->nodeValue . "<br />"; } ?> //SimpleXML.php <?php $xml = simplexml_load_file("test.xml"); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; } ?>

RSS Feeds
//read-rss-from-side.php <? // Create an XML parser $xml_parser = xml_parser_create(); function characterData($xml_parser, $data) { print ($data); } // Set the functions to handle opening and closing tags #xml_set_element_handler($xml_parser, "startElement", "endElement"); // Set the function to handle blocks of character data xml_set_character_data_handler($xml_parser, "characterData"); // Open the XML file for reading $fp = fopen("http://www.sitepoint.com/rss.php","r") or die("Error reading RSS data."); // Read the XML file 4KB at a time while ($data = fread($fp, 4096)) { // Parse each 4KB chunk with the XML parser created above xml_parse($xml_parser, $data, feof($fp)) // Handle errors in parsing or die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } // Close the XML file fclose($fp); // Free up memory used by the XML parser xml_parser_free($xml_parser); ?>

Image / Graphics Handling in PHP


//rectangle-text-line.php <?php $im = ImageCreate(200,200); // Create a new palette based image $blue = ImageColorAllocate($im,0x00,0x00,0xFF); // Allocate a color for an image $green = ImageColorAllocate($im,0x00,0xFF,0x00); ImageFilledRectangle($im,50,50,150,150,$green); ImageString($im, 3, 25, 160, 'A Simple Text String', $green); // Draw a string horizontally // imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color ) ImageLine($im, 60, 60, 120, 120, $blue); // imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) header('Content-Type: image/png'); ImagePNG($im); ImageDestroy($im); ?>

Project Work on CRUD functionality Sample 1


//connection.inc.php <? session_start(); mysql_connect("localhost","root","tashidaw") or die("Could not connect"); mysql_select_db("db") or die("Could not select the database"); ?>

//login.php

<?php require_once "connect.inc.php"; ?> <script language="javascript"> function init(){ document.getElementById("login").focus(); } window.onload=init; function validate(){ var login = document.getElementById("login"); var pwd = document.getElementById("passwd"); if(login.value.length < 1){ alert("Please enter the username!"); login.focus(); return false; } if(pwd.value.length < 1){ alert("Please enter the password!"); pwd.focus(); return false; } document.frmLogin.submit(); return true; } </script> <?php if(isset($_POST["login"])){ $result=mysql_db_query("db","SELECT * FROM login") or die(mysql_error()); $row=mysql_fetch_array($result) or die(mysql_error()); if(mysql_real_escape_string($_POST["login"]) == $row["username"] && md5($_POST["passwd"])==$row["password"]){ $_SESSION['userId']=$row["id"]; $flag=1; } if($flag == 1){ header("location:db.php"); } else { echo "<p align='center'><font color='#FF0000'>Error in Login, Please try again!</font></p>"; } } echo "<form name='frmLogin' action='login.php' method='post'>"; echo "<table border='1' align='center'>"; echo "<tr><th align='left'>User Name:</th><td><input type='text' name='login' id='login'></td></tr>"; echo "<tr><th align='left'>Password:</th><td><input type='password' name='passwd' id='passwd'></td></tr>";

echo "<tr><td colspan='2'><input onClick='validate()'></td></tr>"; echo "</table>"; echo "</form>"; ?>

type='button'

name='btnSubmit'

value='

Login

'

//db.php

<? require_once "connect.inc.php"; if(isset($_SESSION["userId"])){ ?> <script language="javascript"> function cancelForm(){ window.location.href='db.php'; } </script> <?php switch($_GET['action']){ case delete:$ID=$_GET["id"]; mysql_query("DELETE FROM user WHERE id=$ID;"); break; case edit:$ID=$_GET["id"]; if(isset($_POST["submit"])){ $userID = $_POST["id"]; mysql_query("UPDATE user SET name='$name' WHERE id=$userID;"); }else{ $result=mysql_query("SELECT * FROM user WHERE id=$ID;"); $row=mysql_fetch_array($result); echo "<div align='center'>"; echo "<form name='frm_update' action='db.php?action=edit' method='post'>"; echo "<b>Name:</b><input type='text' name='name' value='$row[name]'><br>"; echo "<input type='hidden' name='id' value='$row[id]'><br>"; echo "<input type='submit' name='submit' value='Update'/>"; echo "<input type='button' value='Cancel' onClick='cancelForm()'/>"; echo "</form>"; echo "</div>"; } break; case add: if(isset($_POST["submit"])){ mysql_query("INSERT INTO user(name) VALUES('$name');"); }else{ echo "<div align='center'>"; echo "<form name='frm_add' action='db.php?action=add' method='post'>"; echo "<b>Name:</b><input type='text' name='name'><br>"; echo "<input type='submit' name='submit' value='Add'/>"; echo "<input type='button' value='Cancel' onClick='cancelForm()'/>"; echo "</form>"; echo "</div>"; } break;

case logout: header("location:login.php"); session_destroy(); exit(); } $result=mysql_query("Select * from user order by id;"); echo "<table border='1' width='25%' align='center'>"; echo "<tr bgcolor='#00FF00'><th align='center'>ID</th>"; echo "<th align='center'>Name</th>"; echo "<th align='center'>Edit</th>"; echo "<th align='center'>Delete</th>"; $colorIndex=0; while($row=mysql_fetch_object($result)){ ?> <tr <? if((++$colorIndex%2)==0){ ?> bgcolor="#FFCC66" <? } else { ?> bgcolor="#FFFF99" <? } ?>> <?php echo "<td>".$row->id."</td>"; echo "<td>".$row->name."</td>"; echo "<td><a href='db.php?action=edit&id=".$row->id."'>Edit</a></td>"; echo "<td><a href='db.php?action=delete&id=".$row->id."'>Delete</a></td>"; echo "</tr>"; } echo "<tr bgcolor='#336699'><td colspan='2'><a href='db.php?action=add'><font color='#FFFFFF'>Add</font></a></td>"; echo "<td colspan='2'><a href='db.php?action=logout'><font color='#FFFFFF'>Logout</font></a></td></tr>"; echo "</table>"; } else{ header("location:login.php"); session_destroy(); exit(); } ?>

PROJECTONCRUDFUNCTIONALITYSAMPLE2 default.php
<?php session_start(); ?> <HTML> <HEAD><TITLE>LOGIN</TITLE> </HEAD> <BODY> <h2>Login Details</h2> <hr/> <?php include("conn.php"); $_SESSION['uname']=$_POST['user_name']; while($row = mysql_fetch_array($result)){ if($_POST['user_name']==$row[name] && md5($_POST[passwd])==$row[passwd]) { ?> <script language = "javascript"> window.location.href="task.php"; </script> <?php } } ?> <FORM NAME = "myform" ID = "myform" METHOD="POST" ACTION = "default.php"> LOGIN ID : <INPUT TYPE = "TEXT" NAME = "user_name" ID="user_name"/> PASSWORD : <INPUT TYPE = "PASSWORD" NAME = "passwd" ID = "passwd"/> <INPUT TYPE = "SUBMIT" VALUE="LOGIN"/> </FORM> <br/> <strong>Sample ID and Password</strong><br/> ID : test <br/> password : test </BODY> </HTML>

Conn.php
<?PHP mysql_connect("localhost","root",""); $result = mysql_db_query("test","select * from mytable;"); ?>

task.php
<?php session_start(); if(!isset($_SESSION['uname']) || strlen($_SESSION['uname'])<1) header("Location: page.php"); ?> <HTML> <HEAD><TITLE>TASK</TITLE> </HEAD> <BODY> <h2>SQL TASKS</h2> <align = "right">Welcome <?php echo $_SESSION['uname'];?></align> <?php include("links.txt"); ?> </BODY> </HTML>

links.txt
<hr/>| <a href="add.php"> ADD </a> | <a href="edit.php"> EDIT </a> | <a href="view.php"> VIEW </a> | <a href="del.php"> DELETE </a> | <a href="default.php"> LOG OUT </a> | <hr/>

add.php
<?php session_start(); if(!isSet($_SERVER['HTTP_REFERER']) || !isset($_SESSION['uname']) || strlen($_SESSION['uname'])<1) header("Location: page.php"); ?> <HTML> <HEAD><TITLE>ADD MEMBER</TITLE> </HEAD> <BODY> <h2>SQL ADD TASKS [ADD USER]</h2> <align = "right">Welcome <?php echo $_SESSION['uname'];?></align> <?php include("links.txt");?> <form id = "myform1" name = "myform1" method = "POST" action = "add_after.php">

<table> <tr> <td>Name : </td><td><input type = "text" name = "add_name" id="add_name" size = "30"/></td> </tr> <tr> <td>Password : </td><td><input type = "password" name = "add_pass" id="add_pass" size = "30"/></td> </tr> <tr/> <tr> <td></td><td><input type = "submit" value = "ADD USER"/></td> </tr> </table> </form> </BODY> </HTML>

add_after.php
<?php session_start(); if(!isSet($_SERVER['HTTP_REFERER']) || !isset($_SESSION['uname']) || strlen($_SESSION['uname'])<1) header("Location: page.php"); ?> <HTML> <HEAD> <TITLE>Edit in DB</TITLE> </HEAD> <BODY> <?php include("links.txt"); ?> <?php include("conn.php"); //$result = mysql_db_query("test","select * from mytable where name=;"); $var1 = $_POST['add_name']; $var2 = md5($_POST['add_pass']); if($var1!="" && $var2!=""){ mysql_db_query("test","insert into mytable Values('$var1','$var2');"); print("<h1>Records Successfully Inserted</h1>"); } else print("<h1>INVALID INSERTION</h1>");

?> </BODY> </HTML>

view.php
<?php session_start(); if(!isset($_SESSION['uname']) || strlen($_SESSION['uname'])<1) header("Location: page.php"); ?> <HTML> <HEAD> <TITLE>View DB</TITLE> </HEAD> <BODY> <h2>table entries</h2> <?php include("links.txt"); include("conn.php"); $result = mysql_db_query("test","select * from mytable;"); print("<TABLE BORDER = '1'>"); print("<tr>"); print("<th>NAME</th>"); print("<th>PASSWORD</th>"); print("</tr>"); while($row = mysql_fetch_array($result)){ print("<tr>"); print("<td>$row[name]</td>"); print("<td>$row[passwd]</td>"); print("</tr>"); } print("</TABLE>"); mysql_free_result($result); ?> </BODY> </HTML>

del.php

<?php session_start(); if(!isSet($_SERVER['HTTP_REFERER']) || !isset($_SESSION['uname']) || strlen($_SESSION['uname'])<1) header("Location: page.php"); ?> <HTML> <HEAD> <TITLE>DELETE DB</TITLE> </HEAD> <BODY> <?php include("links.txt"); ?> <?php include("conn.php"); $varS=$_POST['radiobutton']; //delete from fruit where status = 'rotten'; mysql_db_query("test","delete from mytable where name= '$varS'"); print("<h1>Records Successfully Deleted</h1>"); ?> </BODY> </HTML>

edit.php
<?php session_start(); if(!isSet($_SERVER['HTTP_REFERER']) || !isset($_SESSION['uname']) || strlen($_SESSION['uname'])<1) header("Location: page.php"); ?> <HTML> <HEAD> <TITLE>update bd</TITLE> </HEAD> <BODY> <?php include("links.txt"); ?> <?php include("conn.php"); $varS=$_SESSION['ed_name'];

$var1 = $_POST['EDIT_NAME']; $var2 = md5($_POST['EDIT_P']); if($var1!="" && $var2!=""){ mysql_db_query("test","update mytable set passwd = '$var2' where name='$varS'"); mysql_db_query("test","update mytable set name = '$var1' where name='$varS'"); print("<h1>Records Successfully Inserted</h1>"); } else print("<h1>INVALID INSERTION</h1>"); ?> </BODY> </HTML>

Department of Information Technology


Ministry of Information and Communications Royal Government of Bhutan

TrainingFeedBack
1. 2. 3. 4. 5. Participant Name : Organization : Contact Number : +975 Official Email Address : IM Email Address :

EvaluationofParticipants
1. Beginner 1 2 3 4 5 2 .Intermediate 3 .Good 1 Rate yourself in Basic Programming knowledge Familiarity with C, C++, PERL, JAVA Have you any experience in PHP before the training session Understanding of OOP concept Knowledge of PHP5 classes and objects 4. Expert 2 3 4

CourseEvaluation
1. Strongly Agree 1 2 3 4 5 6 2 .Agree 3 .Neutral 4. Disagree 5.Strongly Disagree 1 2 3 4 5 I found this course interesting and relevant The materials used were relevant and interesting The course objectives were clearly presented and met I would recommend this course to others This course was interesting, and stimulated my interest in the subject matter Presentation was very comprehensive with good illustrations

InstructorEvaluation
1. Strongly Agree 1 2 .Agree 3 .Neutral 4. Disagree 5.Strongly Disagree 1 2 3 4 5 Instructor spoke clearly

Post Box No. 482, Thori Lam, Thimphu Bhutan, Tel: (int+975) 2-322925, 2-323215, Fax: +975-2-328440, Email: webmaster@dit.gov.bt Website: http://www.dit.gov.bt

Department of Information Technology


Ministry of Information and Communications Royal Government of Bhutan

2 3 4 5 6 7 8

Instructor explained subject matter clearly and comprehensively Instructor was stimulating and interesting to listen to The materials presented were well organized. Instructor had been very interactive with participants This instructor encouraged class participation Lessons were taught at a good pace Instructor had been helpful in resolving issues and responding participants questionnaires

How do you plan to implement the training session and the knowledge imparted when you go back to your organization?

Any Comments:

ThankYou
INSTRUCTOR NAME: VISHANTA RAYAMAJHI PROFESSION: INTERNATIONAL ICT EXPERT COUNTRY: NEPAL (KATHMANDU CITY) EMAIL: vishanta.rayamajhi@gmail.com, r_vishanta @ Yahoo and MSN IMs CONTACT NUMBER: +977 - 9851021580

Post Box No. 482, Thori Lam, Thimphu Bhutan, Tel: (int+975) 2-322925, 2-323215, Fax: +975-2-328440, Email: webmaster@dit.gov.bt Website: http://www.dit.gov.bt

Você também pode gostar