PHP
PHP
PHP
Submitted by:
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.
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
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
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
13
15
16
17
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
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,
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
"a is bigger than b";} $b) "a is equal to b";} "a is smaller than b;}
32
strstr is a boolean function which checks if its 33 2nd argument is a substring of its 1st
?>
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, )
45
46
A hash array
$mothers = array (tom"=>mary", mick"=>ann", bill"=>orla");
47
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
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_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_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_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_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_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
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
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
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
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
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
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
addslashes
Quote string with slashes
bin2hex
Convert binary data into hexadecimal representation
chop
Alias of rtrim()
chr
Return a specific character
70
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
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
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
levenshtein
Calculate Levenshtein distance between two strings
localeconv
Get numeric formatting information
ltrim
Strip whitespace from the beginning of a string
74
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
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
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
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
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
stristr
Case-insensitive strstr()
strlen
Get string length
strnatcmp
String comparisons using a "natural order" algorithm
80
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
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
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
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
ucwords
Uppercase the first character of each word in a string
vprintf
Output a formatted string
vsprintf
Return a formatted string
85
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
(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
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
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
include()
includes and evaluates the specified file
include_once()
included only once
require_once ()
included only once
96
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>
99
Example (cont.)
100
Example (cont.)
101
Example (cont.)
102
TASK
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
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
112
(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
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("[email protected]", "My Subject", "Line 1\nLine 2"); ?>
119
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
122
} ?>
} ?>
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"; }
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
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
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');
128
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:
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
137
(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
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
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 <b>bold</b> strip_tags() is the main function used; echo strip_tags(<script>alert(test);</script>); will
output alert(test);
146
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
150
Thank you
Er. Vishanta Rayamajhi International ICT Expert +977 98510 21580 [email protected] IM (r_vishanta in Yahoo and MSN)
151
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(); ?>
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)
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>
$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>
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.
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.
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=”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.
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', '[email protected]'); 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', '[email protected]', 'jbloggs', 'jb123');
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; } ?>
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 = "[email protected]"; $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 = "[email protected]"; $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 ?>
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"> </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"> </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
= = = =
// 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:
// 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,
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>";
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 = "[email protected]"; // 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); ?>
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>
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); ?>
//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>";
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>");
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>
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: [email protected] Website: http://www.dit.gov.bt
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: [email protected], 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: [email protected] Website: http://www.dit.gov.bt