PHP

 A server-side, cross-platform, HTML-embedded Lecture 28 scripting language used to create dynamic Web pages (like Perl open source).

 We can write PHP code directly into HTML and don’t PHP need to worry about CGI (like Java Server Pages).

April 6, 2005  Looks like Perl and knowledge of one can help you understand the other.

needs to be configured to parse files with certain extensions (e.g. or phtml) appropriately.

PHP Serve-side Scripting

 Server-side scripting  SSI: Server-side includes:  Most CGI tools:  very old scripting language  write page headers, define layout, etc.  mostly provides #include  few really dynamic parts, most static  PHP:  have to write many static print statements  complete language  Let’s design pages by writing static HTML documents  free with pieces of code inside:  integrates nicely into Apache, IIS, other servers  code is executed at request time  pages can take parameters  ASP:  Scripting languages come with libraries providing  Microsoft version of PHP functions specially designed for Web programming:  language is essentially Basic  e.g.: URL/parameters manipulations, database gateways, ...  JSP: Java Server Pages  Java version

PHP PHP

 Most popular third-party module for Apache:  code and extensive documentation available from PHP Test http://www.php.net/  Pieces of code are enclosed into tags  Example: PHP Test PHP Test Hello World!

1 Parameter Decoding Parameter Decoding

 Each PHP script can be invoked as a CGI.  Each PHP script can be invoked as a CGI.  Parameters are decoded automatically and appear to the script as  Parameters are decoded automatically and appear to the script as normal variables. normal variables.  Example:  Example: http://www.cse.nd.edu/~cpoellab/myphp.php?x=2&y=hello http://www.cse.nd.edu/~cpoellab/myphp.php?x=2&y=hello

PHP Test PHP Test ?>

More Preset Variables Variables

 PHP creates many other variables automatically:  All names begin with $ e.g. $variable  $HTTP_USER_AGENT, $REMOTE_ADDR, etc.   list: Alphabetic character or underscore (_) must  Example: follow $  Remaining chars are alphanumeric or

You are using Internet Explorer
underscore
You are not using Internet  Names are case-sensitive $A is not $a Explorer
 Types determined by first assignment  Did you notice that you can split a PHP program into pieces separated by HTML?

Data Types String Handling

 Integer  Characters within strings can be obtained via  Whole numbers –2,147,483,648 to 2,147,483,647 subscripting  Floating Point  Subscripts start at 0  Decimal values in the range 1.7E-308 to 1.7E308  String $hello = “Hello World”  Sequence of characters e.g. “Hello World” $hello[1] = ?

2 Outputting a String Length of a String

 The function echo() outputs a string to the  The function strlen() returns a string’s length standard output e.g. echo(“Hello World”); $hello=“Hello World”

$astring = “Hello World”; The value of strlen($hello) is 11 echo($astring);

Getting a Number from a Expressions String

 Includes normal arithmetic operations  Use the string in a calculation  $i=$i+1 or $i++  PHP converts as much as it can to a number  $i=$i-1 or $i--  Also / (divide) and * (multiply)  % is the modulo operation $var=“1234”  May use brackets to specify precedence $num=$var[2] + 5  Statements separated by semi-colons  Expressions evaluate to true or false $num contains the number...?

PHP Control Structures PHP Arrays

 Like all languages, PHP has control structures:  Very useful feature: array variable type (set “teacher” if ($x==0) { “You” => “student” ... } }; elseif ($x==1) { $role[“You”] = “student”; ... $me = $role[“Poellabauer”]; } ?>

3 PHP Arrays PHP Arrays

 Special case: array indexed by integers:  What about array of arrays?

$students = array ( $names = array(“Poellabauer”, “You”, “Your neighbor”); “You” => array ( “name” => “yourname”, “student nb” => 1234), $myname = $names[0]; “Another” => array ( “name” => “hisname”, “student nb” => 5678), “Foobar” => 42 $names[3] = “Another student”; );

$you = $students[“You”]; $yourname = $students[“You”][“name”];

print(“

”); print_r($students); // This will print a human-readable version of $students print(“
”);

print_r print_r

 Array (  apple $a = array ('a' => 'apple', 'b' => 'banana', 'c' [b] => banana => array ('x', 'y', 'z')); [c] => Array ( print_r ($a); [0] => x ?> [1] => y [2] => z 
) )

PHP Functions PHP Functions

 You can define functions:  Predefined functions: tons! function addition($x, $y) {  Classified into categories: return $x+$y;  Apache, arrays, Aspell, BC, Bzip2, Calendar, CCVS, COM, Classes/Objects, ClibPDF, Crack, } CURL, Cybercash, CyberMUT, Cyradm, ctype, $foo = addition(31,11); dba, Date/Time, dBase, DBM, dbx, DB++, DIO, Directories, DOM XML, .NET, Errors and Logging, FrontBase, filePro, Filesystem, FDF, FriBiDi, FTP, Functions, gettext, GMP, HTTP, Hyperwave, ...  check http://www.php.net/manual/en/

4 PHP Functions Getting Data From Client

 Look at following code:  Data is often supplied to server side [Last modified: %s] “, date(“D, d M  Indicated by the

tag Y H:i:s”, filemtime(“$x”))); }  Specifies HTTP method and field names ?>  Field names become variables in PHP scripts  Field name myfield becomes $myfield Download your new assignment

A Simple Form Simple Form Output

Multiply Form

Enter multiplier

PHP Script Output

Times Table * =

5 Getting it on the Server Manipulating HTTP Headers

 Treat PHP scripts like ordinary HTML pages  By default, PHP scripts are assumed to generate HTML:  Except save in files called .php  Content-Type field of response defaults to text/html  Suitably equipped Web Server does the rest  You can force it otherwise:  You can only manipulate HTTP headers BEFORE displaying anything. This won’t work:

Access Control Access Control

 You may want to control access to certain pages:  You can also use HTTP basic authentication:  administration pages, secrets, ...  first HTTP request: return HTTP code 401 “please  Check IP address: authenticate yourself” if ($REMOTE_ADDR!=“130.207.7.245”) {  client types username and password header(“HTTP/1.0 403 forbidden access”);  another HTTP request containing both: authorized to enter print(“You are not authorized to access my diary”);  PHP has standard variables for both: exit; $PHP_AUTH_USER and $PHP_AUTH_PW }   will only work if you know exactly who can send requests Documents are not encrypted: from that address  even username/password are sent in clear text  what if you want to access page from Cybercafe?  anyone who intercepts the request can gain access

Access Control Access Control

6 Session Tracking Session Tracking

 By default, a web server is stateless.  Send pieces of data (“cookies”) to client:  client attaches same cookie to each further request  However, often you want to establish a  if server sends a different cookie to each new client, then it can session: track which request has been made by which client  Cookie:  keep memory of past requests of user  name (“userid”)  example: e-commerce:  value (“174848848”)  expiration date (“21 march 2005)  browse to view products  path (“/myshop/”)  add items to shopping basket  server domain (“.cse.nd.edu”)  checkout  security level (“0”)  until cookie expires, name and values will be sent together with every request addressed at a page whose server belongs to “.cse.nd.edu” and whose path starts with “/myshop/”

Session Tracking Session Tracking

 Cookies are transmitted in HTTP response header.  You can store whatever you need to

Session Tracking Summary: Server Side Options

Mod Perl // file attached to this user . ASP

$count++; . PHP print(“You have visited this page $count times”); . Cold Fusion ?>

7 Decision Points Option 1: CGI

. When evaluating which server side framework to . Represents one of the earliest, practical use, you need to consider a number of critical methods for generating web content. factors: . Primarily written in the Perl programming . Ease of development: . How easily can you build new applications? language. . Performance: . Unfortunately, traditional CGI programs . How fast can the framework respond to queries? suffer from scalability and performance . Scalability: problems. . Can the framework scale to thousands, millions of users? . Security: . Let’s examine these two problems… . Are there any inherent security vulnerabilities?

CGI Architecture CGI Architecture

 Browser initiates request . For each browser request, the web server  Web server receives the request. must spawn a new operating system  For each request, web server spawns a new operating system process to execute the CGI/Perl Program. process. Perl 1 Browser 1 Create Web Web New process Perl/ Browser 2 Web Perl Browser Server CGI Server 2 Browser n

Perl n

CGI Architecture Option 2: Fast CGI

. Spawning a new operating system process . Developed by Open Market as an option for developing for each request takes time and memory. faster, more scalable CGI programs. . Fast CGI works by creating a pool of processes for . Hence, traditional CGI programs have handling CGI requests. inherent performance and scalability . When a CGI request comes in, Fast CGI picks one of the problems. processes from the pool and assigns it to the task. . Without the overhead of creating new operating system . Every other server architecture tries to processes, Fast CGI is much faster than traditional CGI. address these problems. . For more information, see http://www.fastcgi.com

8 Option 3: Mod Perl Option 4: ASP

. A module of the Apache Web Server. . Active Server Pages . Embeds the Perl interpreter directly within the web server. . Runs on Microsoft’s Web Server: Internet . No need to start external interpreter. Information Server (IIS) . Also, because Perl is embedded within the Server, Mod . Programmers add ASP code directly into their Perl does not need to create a new process for each HTML pages. request. . When a client requests a page, the Web Server . Like FastCGI, Mod Perl is much faster than traditional CGI. takes the HTML page, runs the ASP code within the . For more information, see: http://perl.apache.org page, and returns a complete HTML page. . Faster than traditional CGI, but only works on Microsoft IIS.

Option 5: Cold Fusion Option 6: PHP

. Developed by Allaire Corporation (now . An open source project written entirely by owned by Macromedia.) volunteers. . Provides excellent database access and . Provides simple, but powerful database database tools. access. . Great platform for rapid prototyping and rapid development. . Also great for rapid development. . For more information: . For additional information: http://www.macromedia.com http://www.php.net

Summary: PHP Summary: PHP

 PHP is a programming language that enables you to  PHP is a programming language that enables you to create interactive web sites. create interactive web sites.  Many good features:  Many good features:  easy to learn.  easy to learn.  fun to use.  fun to use.  free.  free.  ideal for rapid prototyping.  ideal for rapid prototyping.  connects to most databases, including MySQL.  connects to most databases, including MySQL.  available on most systems.  available on most systems.  lots of built-in functions and built-in functionality.  lots of built-in functions and built-in functionality.  Trivia: PHP stands for?  Trivia: PHP stands for? PHP stands for Hypertext Preprocessor

9