300 likes | 502 Views
Short PHP tutorial. About PHP. PHP: Hypertext Preprocessor PHP was created as a framework for writing web applications in C or C++ and making it easy to expose the business logic of these applications to a powerful presentation-layer templating language.
E N D
About PHP • PHP: Hypertext Preprocessor • PHP was created as a framework for writing web applications in C or C++ and making it easy to expose the business logic of these applications to a powerful presentation-layer templating language. • Most people don't really use PHP this way. Over the years the templating language improved both in scope and performance to the point where entire web apps could be written in it. • PHP is not officially a Programming Language per se. • PHP is an interpreted language. That means that there is no explicitly separate compilation step. • Rather, the processor reads the whole file, converts it to an internal form and executes it immediately.
About PHP • Open Source: Apache like BSD-style license • 732 developers • ~25 active (on PHP source) • Documentation in 26 languages • PHP 4.0.0 since May 2000 • PHP 5.0.0beta1 in June 2003 • PHP 4.3.3 in August 2003 • From PHP 0.0 to PHP 3.0 • 1994 - Started writing CGI scripts in C and Perl • 1995 - Combined many CGI scripts into a smaller set of more generic binaries • June 8, 1995 - First official 1.0 release • From: rasmus@io.org (Rasmus Lerdorf) Subject: Announce: Personal Home Page Tools (PHP Tools) • Date: 1995/06/08 • Message-ID: <3r7pgp$aa1@ionews.io.org>#1/1 organization: none • newsgroups: comp.infosystems.www.authoring.cgi • Announcing the Personal Home Page Tools (PHP Tools) version 1.0. These tools are a set of small tight cgi binaries written in C. They perform a number of functions including: . Logging accesses to your pages in your own private log files . Real-time viewing of log information . Providing a nice interface to this log information . Displaying last access information right on your pages . Full daily and total access counters . Banning access to users based on their domain . Password protecting pages based on users' domains . Tracking accesses …
Usage • Usage Stats for April 2007 • PHP: 20,917,850 Domains • 1,224,183 IP Addresses • Source: Netcraft • http://www.php.net/usage.php
Server side • PHP is a Server-side language even though it is embedded in HTML files much like the client-side JavaScript language, PHP is server-side and all PHP tags will be replaced by the server before anything is sent to the web browser. • So if the HTML file contains:<html><?phpecho "Hello World"?></html> • What the end user would see with a "view source" in the browser would be: <html>Hello World</html>
Embedding PHP • The 4 available tag styles • <html><body><? echo 'Short Tags - Most common' ?><br /><?phpecho 'Long Tags - Portable' ?><br /><%= 'ASP Tags' %><br /><script language="php">echo 'Really Long Tags - rarely used';</script><br /></body></html> • Output • Short Tags - Most commonLong Tags - Portable<%= 'ASP Tags' %> Really Long Tags - rarely used
Language syntax • C-Like syntax: • <?for ($loop = -5; $loop < 5; $loop++) { if ($i< 0) { echo "-"; } elseif ($i> 0) { echo "+"; } echo "$loop<BR>\n";}while(--$loop) { switch($i% 2) { case 0: echo "Even<BR>\n"; break; case 1: echo "Odd<BR>\n"; break; }}do { echo "$loop<BR>";} while (++$loop < 10);?>
Language Syntax continued • Syntax and switching modes • <? • if(strstr($_SERVER['HTTP_USER_AGENT'],"MSIE")) { • // end PHP code • ?> • <b>You are using Internet Explorer</b> • // return to PHP code then end PHP code • <? } else { ?> • <b>You are not using Internet Explorer</b> • // return to PHP code then end of script • <? } ?> • Output • You are not using Internet Explorer
Language Basics • Variables and Expressions • <?php $foo= 1;$bar = "Testing";$xyz = 3.14;$foo= $foo+ 1;?> • Arrays • <?php $foo[1] = 1; $foo[2] = 2;$bar[1][2] = 3;?> • Functions • <?phpphpinfo();foo();$len= strlen($foo);?> • Control Structures • if • else • elseif • while • do..while • for • foreach • breakcontinue • switch • declare • return • require() • include() • require_once() • include_once()
Language Basics: Basic Data types • Numbers (integers and real) • <?php $a = 1234;$b = 0777;$c = 0xff;$d = 1.25; echo "$a $b $c $d<br />\n";?> • Output • 1234 511 255 1.25 • Strings • <?php// Single-quoted$name = 'Rasmus $last'; • // Double-quoted$str= "Hi $name\n"; • echo $str;?> • Output • Hi Rasmus $last • Booleans • <?php $greeting = true; if($greeting) { echo "Hi Carl";$greeting = false; }?> • Output • Hi Carl • Dynamic Typing • Don't have to declare types • Automatic conversion done • <?phpecho 5 + "1.5" + "10e2";?> • Output • 1006.5
Language Basics: Arrays • Ordered Arrays • <?php $a[0] = 1;$a[1] = "foo";$a[] = 1.57;?> • Associative arrays • <?php$catch_it['cat'] = "mouse";$catch_it['dog'] = "cat";?> • Manipulating • Sorting: sort(), rsort(), ksort(), usort(), array_multisort() • Traversal: reset(), end(), next(), each(), current(), key(), array_walk() • Advanced: array_diff(), array_intersect(), array_merge(), array_merge_recursive(), array_slice(), array_splice() and lots more...
Variables Scope • Static Variables • <?phpfunction bar2() { static $i=0; return ++$i;}echo bar2()."<br>\n";echo bar2()."<br>\n";?> • Output • 1 • 2 • Global Scope • The global scope spans all included files. That is, $foo will be visible in file.php. • <?php $foo= 1; include 'file.php';?> • Function Local Scope • If you wish to access a global variable from within a function, you have to use the global keyword to tell the function that it should use the variable from the global scope instead of the function's own local scope. • <?phpfunction bar() { global $foo; echo $foo;}$foo = 1;bar();?> • Output • 1
PHP doesn't make a distinction between numeric and string comparison operators. Numeric test operators • An overview of the numeric test operators: • ==: equal • !=: not equal • <: less than • <=: less than or equal to • >: greater than • >=: greater than or equal to • All these operators can be used for comparing two numeric values in an if condition.
Other Operators • Truth expressions • three logical operators: • and: and (alternative: &&) • or: or (alternative: ||) • not: not (alternative: !) • Increment/decrement operators, which are essentially shorthand ways of adding or subtracting one from a number: • $a = 5; $a++; // $a has been incremented by 1, and now equals 6 • $a--; // $a has been decremented by 1, and now equals 5 • $b = 5 * $a++; • // Note that the incrementing happens after the evaluation: • // First, $b is calculated to be 25. • Then, $a is incremented to become 6 • // If you want $a to be incremented first, put the ++ in front of it • // as follows: • $b = 5 * ++$a; // $a incremented to 7; $b becomes 35 • $c = 100; • $c -= ++$b + $a++; • // $b becomes 36; $c is calculated to be • // 100 - ( 36 + 7 ); finally, $a becomes 8
Control structures • Beyond the basic if..else structure, there are loops. Loops bring the power of automation to your script. • #print numbers 1-10 in three different ways • $i = 1; • while ($i<=10) { • print "$i\n"; • $i++; • } • for ($i=1;$i<=10;$i++) { • print "$i\n"; • } • foreach $i (1,2,3,4,5,6,7,8,9,10) { • print "$i\n"; • }
User Defined Functions • Functions generally take some type of input and return some type of output (although, sometimes either input or output can be omitted). • Typical User Defined Function • <?phpfunction log_data($user, &$data) {mysql_query("INSERT INTO userdata VALUES ('".uniqid()."', '$user', '$data')");}?> • Pass-by-reference • <?phplog_data($PHP_AUTH_USER, $data); ?> • Default values • <?phpfunction head($title="Default Title") {?> <HTML><HEAD><TITLE><? echo $title ?> </TITLE></HEAD><BODY><?}head();?>
String manipulation • Substr • <?php$str = "Fast String Manipulation";echo substr($str,0,4) . substr($str,-9);?> • Output • Fastipulation • Explode • <?php$a = explode(":", "This:string:has:delimiters.");while (list(,$value) = each($a)) { if (strcmp($value, "has") == 0) { echo "had "; } else echo $value." ";}?> • Output • This string had delimiters.
Regular expressions Examples: 1. Clean an HTML formatted text 2. Grab URLs from a Web page 3. Transform all lines from a file into lower case • \b: word boundaries • \d: digits • \n: newline • \r: carriage return • \s: white space characters • \t: tab • \w: alphanumeric characters • ^: beginning of string • $: end of string • .: any character • [bdkp]: characters b, d, k and p • [a-f]: characters a to f • [^a-f]: all characters except a to f • abc|def: string abc or string def • *: zero or more times • +: one or more times • ?: zero or one time • {p,q}: at least p times and at most q times • {p,}: at least p times • {p}: exactly p times
Regular expressions continued • Posix Style • <?phpecho ereg_replace('will be ([[:alpha:]]+)', 'has been \1', 'This string will be modified.');?> • Output • This string has been modified. • Perl Style • <?phpecho preg_replace('/will be ([\w\s]+)/', 'has been \1', 'This string will be modified.');?> • Output • This string has been modified.
Form Handling • Forms are used to get information from users. HTML contains tags that allow you to create forms, and the Hypertext Transfer Protocol (HTTP) has features that place information obtained from forms into specified variables, for use by PHP programs. Generally, a PHP program will process the form information, perhaps save some of the information in a file, and then output something to the user (e.g., in the simplest case, "Your information was received"). • Form: • <form action="<?=$PHP_SELF?>" method="POST">Your name: <input type=text name=name><br>You age: <input type=text name=age><br><input type=submit></form> • Output • Your name: • Your age:
Form Handling • Receiving Script for the form: • Hi <?echo $name?>. You are <?echo $age?> years old. • Register Globals • Some feel that automatically populating the symbol table with user-supplied data can lead to insecure programs, which to some extent is correct. To combat this the register_globals setting is off by default in PHP 4.2 and later. • Hi <?echo $_POST['name'] ?>. You are <?echo $_POST['age'] ?> years old.
Global variables • PHP automatically creates global variables containing data from a variety of external sources. This feature can be turned off by turning off the register_globals setting. With register_globals you can access this data via a number of special associative arrays listed below. • $_GET['foo']='bar‘ • http://www.php.net/index.php?foo=bar • $_POST['foo']='bar‘ • <form action="script.php" method="POST"><input type="text" name="foo" value="bar"></form> • $_COOKIE['foo']='bar‘ • <?phpSetCookie('foo','bar');?> • $_REQUEST['foo']='bar‘ • <?phpSetCookie('foo','bar');?> • $_SERVERS • special variables set by your web server. You can get a list of what is set by running this code on your server: <?phpforeach($_SERVER as $key=>$val) { echo '$_SERVER['.$key."] = $val<br>\n";}?> • $_SERVER[DOCUMENT_ROOT] = /local/Web/sites/talks$_SERVER[HTTP_ACCEPT] = text/xml,application/xml,application/xht...$_SERVER[HTTP_ACCEPT_CHARSET] = ISO-8859-1,utf-8;q=0.7,*;q=0.7… • $_ENV • Environment variables that were present at server startup time. Note that environment variables created by PHP using putenv() will not be shown here, nor do they persist beyond the request. $_ENV[PWD] = /$_ENV[BOOT_FILE] = /boot/vm2422-rc2… • $_FILES • Used for the RFC1867 file upload feature. $_FILES['userfile']['name']$_FILES['userfile']['type']$_FILES['userfile']['size']$_FILES['userfile']['tmp_name'] • $HTTP_RAW_POST_DATA • When the mime type associated with the POST data is unrecognized or not set, the raw post data is available in this variable.
Files • readfile() • <?php readfile("/proc/cpuinfo")?> • processor : 0 • vendor_id : GenuineIntel • cpu family : 6 • model : 8 • model name : Pentium III (Coppermine) • stepping : 10 • cpu MHz : 993.380 • cache size : 256 KB • … • And a new PHP 4.3.0 Function • file_get_contents() • <?php • $contents = file_get_contents("/proc/cpuinfo"); • $contents = trim($contents,"\n"); • echonl2br($contents); • ?> • Output • processor : 0 • vendor_id : GenuineIntel • …
More about file management Reading from a file <?php $file = fopen("sample.txt", "r"); while (!feof($file)) { echo fgets($file), "<BR>"; }?> Reading from a URL <?php $file = fopen("http://www.php.net/file.txt", "r"); ?> Writing to a file <?php $file = fopen("agent.log", "a");fputs($file, $HTTP_USER_AGENT."\n");?> An example program that downloads a webpage.<?phpif ($argc< 2) { die ("You must specify a URL\n");}$url= $argv[1];if (!preg_match("@^\S+\://@", $url)) { die ("You must specify a URL identifier\n");}print file_get_contents($url);?>
Installing PHP • “Many people know from their own experience that it's not easy to install an Apache web server and it gets harder if you want to add MySQL, PHP and Perl. XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl.” apachefriends.org • An integrated Apache + PHP package is available from apachefriends.org • http://www.apachefriends.org/wampp-en.html
Resources • Home Page: http://www.php.net • Manual: http://php.net/manual • Tutorial: http://php.net/tut.php • Books: http://php.net/books.php • Downloads: http://www.php.net/downloads.php • LAMP distribution: http://www.apachefriends.org/index-en.html