21/12/2001 Adv.Network Programming-PHP 1
CMPE 587 Adv.Network Programming
Şeniz Demir, Nurcan TezcanŞeniz Demir, Nurcan Tezcan
Boğaziçi UniversityBoğaziçi University
20012001
PHP Scripting Language
21/12/2001 Adv.Network Programming-PHP 2
OutlineOutline
• Definition
• Architecture
• Features
• Database Connection
• Security in PHP
• Session Tracking
• Functions
• Conclusion
• Resources
21/12/2001 Adv.Network Programming-PHP 3
A popular server-side scripting language with extensive DB support.
PHP provides the "glue" to link together: Web browser, Web server,HTML, forms, SQL, RDBMS
and provide a basis for Web-based database applications.
21/12/2001 Adv.Network Programming-PHP 4
Platforms:Platforms: • UNIX (all variants) • Win32 (NT/W95/W98/W2000) • QNX • MacOS (WebTen) • OSX ,OS/2 ,BeOS
Server Interfaces:Server Interfaces:• Apache module (UNIX,Win32) • CGI/FastCGI • thttpd ,fhttpd , phttpd • ISAPI (IIS, Zeus) • NSAPI (Netscape iPlanet) • Java servlet • AOLServer • Roxen/Caudium module
21/12/2001 Adv.Network Programming-PHP 5
21/12/2001 Adv.Network Programming-PHP 6
The PHP language has the following characteristics: •C-like syntax (more C-like than Perl)
•"loose" attitude to types (determined by context)
•very easy to manipulate strings •extensive libraries of functions (including DB access for most RDBMS)
•some attempt at object-orientation •comments introduced via # or //
PHP programs are typically executed within Web server.
FeaturesFeatures
21/12/2001 Adv.Network Programming-PHP 7
HTML EmbeddingHTML Embedding
<HTML><HEAD><TITLE>Search results for "<?php print $query; ?>"</TITLE></HEAD><BODY>
Traditional CGI Programming#!/usr/bin/perl
print "<HTML><HEAD>\n";print "<TITLE>Search results for \"$query\"</TITLE>\n";print "</HEAD>\n";print "<BODY>\n";
PHP
21/12/2001 Adv.Network Programming-PHP 8
Variables Variables
• No variable declarations required; variables created by assignment. • All variable names must be preceded by $ (eg: $i, $i++, $++i) • Type of variable is set to that of last assigned value. • Can check/set variable type via gettype/settype functions. • Can convert variable value via casting (e.g. (int), (real), (string), ...) • Default value of unassigned variables is 0 or "" or false.
21/12/2001 Adv.Network Programming-PHP 9
Variables (cont)Variables (cont)
Examples: $foo = 3; # $foo is an int, value 3 $foo = "8"; # $foo is now a string, value "8" $foo = $foo + 2; # $foo is now an int, value 10 $foo = "$foo green bottles"; # $foo is now "10 green bottles" $foo = 3.0 * $foo; # $foo is now double, value 30.0 $foo = (int)$foo; # $foo is now an int, value 30
21/12/2001 Adv.Network Programming-PHP 10
String InterpolationString Interpolation
When variables are used inside string, their value is interpolated, after being converted to a suitable string representation (cf. Perl). Example: $a = 1; $b = 3.5; $c = "Hello"; $str = "a:$a, b:$b, c:$c"; // now $str == "a:1, b:3.5, c:Hello"
21/12/2001 Adv.Network Programming-PHP 11
Arrays Arrays
PHP provides both scalar and associative arrays: $word[0]="a"; $word[1]="the"; $word[2]="this"; ... $mark["ann"]=100; $mark["bob"]=50; $mark["col"]=9; ... $vec[]=1; $vec[]=3; $vec[]=5; $vec[]=7; ...
Arrays can be initialised in a single statement: $word = array("a", "the", "this", ...); $marks = array("ann"=>100, "bob"=>50, "col"=>9, ...); $vec = array(0 => 1, 1 => 3, 2 => 5, 3 => 9, ...);
Multiple-value <SELECT> inputs are passed to PHP as arrays.
21/12/2001 Adv.Network Programming-PHP 12
Variable Variables Variable Variables
In some contexts (e.g. HTML forms), we may have a collection of variables that can't be represented by an array, but we want to iterate over them ... PHP provides a mechanism to dynamically create variable names. e.g: for ($i = 0; $i < $MAX; $i++) { $varname = "myVar$i"; $value = ${$varname}; print "Value of $varname = $value\n"; } Accesses variables called myVar0, myVar1, myVar2, myVar3, ... This is not the same as an array myVar[0], myVar[1], myVar[2], myVar[3], ...
21/12/2001 Adv.Network Programming-PHP 13
Control StructuresControl Structures
Control structures have essentially the same syntax as C/Java.
{ Statement1; Statement2; ... } if (Expression1) Statement1 [elseif (Expression2) Statement2 ...] [else Statementn] switch (Expression1) { case Value1: Statement1; break; ... [case Value2: Statement2; break; ...] } while (Expression) Statement for (Init; Test; Next) Statement
21/12/2001 Adv.Network Programming-PHP 14
Functions Functions
Functions are defined as: function FuncName($arg1, $arg2,, ... ) { Statement; ... return Expression; } Example: // return array of first n integers function iota($n) { for ($i = 1; $i <= $n; $i++) $list[] = $i; return $list; }
21/12/2001 Adv.Network Programming-PHP 15
Handling FormsHandling Forms
<form action="action.php" method="POST">Your name: <input type=text name=name><br>You age: <input type=text name=age><br><input type=submit></form>
Submit Query
Hi <?echo $name?>. You are <?echo $age?> years old.
Name:
Age:
action.php
21/12/2001 Adv.Network Programming-PHP 16
SQL•Adabas D •Empress •IBM DB2 •Informix •Ingres •Interbase •Frontbase •mSQL •Direct MS-SQL •MySQL •ODBC •Ovrimos •Oracle (OCI7,OCI8) •PostgreSQL •Raima Velocis •Solid •Sybase
Others•dBase •filePro (read-only) •dbm (ndbm, gdbm, Berkeley db)
Database SupportDatabase Support
21/12/2001 Adv.Network Programming-PHP 17
MySQL FunctionsMySQL Functions
•mysql_connect (string [server], string [username], string [password])
$link = mysql_connect("localhost", "username", "secret")
•bool mysql_close (resource [link_identifier])mysql_close($link)
•bool mysql_select_db (string database_name, resource [link_identifier])
mysql_select_db("mydb",$link)
• mysql_query (string query [, resource link_identifier])$sql = “SELECT * FROM employees WHERE id=$id” $result = mysql_query($sql)
•array mysql_fetch_array (resource result, int [result_type]) $myrow = mysql_fetch_array($result) $id = $myrow["id"]
21/12/2001 Adv.Network Programming-PHP 18
<html> <body><?php$db = mysql_connect("linus", "root");mysql_select_db("mydb",$db);$sql = "SELECT * FROM employees WHERE id=$id";$result = mysql_query($sql);$myrow = mysql_fetch_array($result); ?>
<form method="post" > <input type=hidden name="id" value="<?php echo $myrow["id"] ?>"> First name:<input type="Text" name="first" value="<?php echo $myrow["first"] ?>"><br> </form>
</ body> </html>
21/12/2001 Adv.Network Programming-PHP 19
EEncryptionncryption/D/Decryptionecryption• include mcrypt library • Four cipher modes
– ECB (electronic codebook)/ for random data
– CBC (cipher block chaining)/ files
– CFB (cipher feedback)/byte streams
– OFB (output feedback) /byte streams
• block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH
21/12/2001 Adv.Network Programming-PHP 20
<?php
$key = "this is a very secret key";
$input = "Let us meet at 9 o'clock at the secret place.";
$encrypted_data = mcrypt_ecb(MCRYPT_TripleDES, $key, $input, MCRYPT_ENCRYPT);
?>
21/12/2001 Adv.Network Programming-PHP 21
SSessionsessions
• preserve data
• stored in cookie or propogate through URL
– session.auto_start is set to 1/automatic
– session_start()/explicit
– session_register()/implicit
21/12/2001 Adv.Network Programming-PHP 22
ExampleExample
$pure_session_id = randomString(40)$exact_session_id = userid.
$pure_session_id
$long_session_id = randomString(100) $long_session_id[47] = $userid[0] $long_session_id[41] = $userid[1]
$long_session_id[ind1] = $pure_session_id[ind2]
21/12/2001 Adv.Network Programming-PHP 23
Persistent ConnectionPersistent Connection
• SQL links that do not close when the execution of your script ends
• Higher efficiency– link creation overhead
• kind of DB• load of the machine where sql server sits
• Connect once and process pages many times
21/12/2001 Adv.Network Programming-PHP 24
Connection HandlingConnection Handling
• Connection status: Normal, Aborted, Timeout
• if the client is disconnected abort the script or not? (default: abort)
• Terminate the script by the built-in script timer (default:30 seconds)
21/12/2001 Adv.Network Programming-PHP 25
Connection Handling FunctionsConnection Handling Functions
• int ignore_user_abort ([int setting])
• int connection_aborted (void )
• set_time_limit()
• int connection_timeout (void )
• int register_shutdown_function (string func)
• int connection_status (void )
21/12/2001 Adv.Network Programming-PHP 26
Socket ProgrammingSocket Programming
• int socket_accept (resource socket)
• int socket_bind (resource socket, string address
[, int port])• bool socket_close (resource socket)• int socket_connect (resource socket,
string address [, int port])
• .......
21/12/2001 Adv.Network Programming-PHP 27
Function set Function set
• FTP functions• IMAP, POP3 functions• Mail functions• Oracle functions• Semaphore and shared memory
functions• Network functions• ..........
21/12/2001 Adv.Network Programming-PHP 28
Conclusion Conclusion
• A server side scripting language• Easier to develop codes• C-like syntax• Lots of built-in modules and
functions
21/12/2001 Adv.Network Programming-PHP 29
ResourcesResources
• www.php.net• www.phpbuilder.com• www.google.de• www.zend.com