570 likes | 830 Views
Nirav Mehta CEO, MagNet WebPublishing Pvt. Ltd. Lighting up the Magic LAMP. Welcome. Welcome What would you like to hear? Objectives of this session Understand what is LAMP Learn how does it light up We are going to go fast! So be prepared!. Introduction.
E N D
Nirav Mehta CEO, MagNet WebPublishing Pvt. Ltd. Lighting up the Magic LAMP
Welcome Welcome What would you like to hear? Objectives of this session Understand what is LAMP Learn how does it light up We are going to go fast! So be prepared!
Introduction GNU/Linux + Apache + MySQL + PHP Open Source, Free! Apache – 66.42% of all active sites MySQL – most popular open source DB PHP – 27.65% of domains, 45.54% of Apache Very popular web development platform
Apache Web Server HTTP daemon Apache Software Foundation Apache Modules httpd.conf What is .htaccess? What is Virtual Hosting?
MySQL Database Fast, stable, most popular open source DB ANSI SQL 99, additional functionalities Data storage formats – MyISAM, InnoDB Transactions, Views / SP / Triggers Good security system, SSL Replication Embedded DB Library
MySQL Basics SQL Basics Create Insert Select Update Delete Alter etc. MySQL command prompt mysql -u username -p dbname
Web - The Good Old Days HTML SSI CGI Programming C Complex Lengthy Perl Fantastic text processing CPAN modules
Handling form data in C #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define ishex(x) (((x) >= '0' && (x) <= '9') || ((x) >= 'a' && (x) <= 'f') || ((x) >= 'A' && (x) <= 'F')) int htoi(char *s) { int value; char c; c = s[0]; if(isupper(c)) c = tolower(c); value=(c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = s[1]; if(isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return(value); } void main(int argc, char *argv[]) { char *params, *data, *dest, *s, *tmp; char *name, *age; puts("Content-type: text/html\r\n"); puts("<html><head><title>Form Example</title></head>"); puts("<body><h1>My Example Form</h1>"); puts("<form action=\"form.cgi\" method=\"GET\">"); puts("Name: <input type=\"text\" name=\"name\">"); puts("Age: <input type=\"text\" name=\"age\">"); puts("<br><input type=\"submit\">"); puts("</form>");
Handling form data in C – II data = getenv("QUERY_STRING"); if(data && *data) { params = data; dest = data; while(*data) { if(*data=='+') *dest=' '; else if(*data == '%' && ishex(*(data+1))&&ishex(*(data+2))) { *dest = (char) htoi(data + 1); data+=2; } else *dest = *data; data++; dest++; } *dest = '\0'; s = strtok(params,"&"); do { tmp = strchr(s,'='); if(tmp) { *tmp = '\0'; if(!strcmp(s,"name")) name = tmp+1; else if(!strcmp(s,"age")) age = tmp+1; } } while(s=strtok(NULL,"&")); printf("Hi %s, you are %s years old\n",name,age); } puts("</body></html>"); }
Handling form data in Perl use CGI qw(:standard); print header; print start_html('Form Example'), h1('My Example Form'), start_form, "Name: ", textfield('name'), p, "Age: ", textfield('age'), p, submit, end_form; if(param()) { print "Hi ",em(param('name')), "You are ",em(param('age')), " years old"; } print end_html;
PHP Makes it Simple! <html><head><title>Form Example</title> </head><body> <form action="form.php" method="POST"> Name: <input type="text" name="name"> <br><input type="submit"></form> <? if($name) { ?> Hi <?echo $name?>! You are <?echo $age?> years old <? } ?> </body></html>
PHP Hypertext Preprocessor Enter PHP!
The PHP Approach Pragmatic approach to the Web Problem Direct and obvious solution for a simple problem Scalability driven by this simplicity Rapid Application Development
The Road to PHP Rasmus Lerdorf June 8, 1995 – first official release October 17, 1995 – public release - PHP/FI June 6, 1998 - PHP3 Currently PHP 4.3
PHP Usage December 2002 On more than 10 million domains About 28% of all the domains
PHP Works Everywhere! Operating Systems UNIX, Linux, Win32, QNX, MacOS, OSX, OS/2, BeOS, AS/400, OS/390 Server Interfaces – CGI and Module Apache, CGI/FastCGI, thttpd, fhttpd, phttpd, ISAPI (IIS, Zeus), NSAPI (Netscape iPlanet), Java servlet, AOLServer, Roxen/Caudium, SRM (Script Running Machine), Tux, pi3web Command Line Interpreter
Embedded Scripting Language Embedded in HTML PHP Tags <? & ?> <?php & ?> <%= & %> <?= & ?> <script language='php'> & </script> Switching between HTML and PHP
Server Side Language Server processes and outputs HTML So if the HTML file contains: <html> <?php echo "Hello World"?> </html> "view source" in the browser: <html> Hello World </html>
Basics – Variables & Operators Variables & Expressions <?php $foo = 1; $bar = "Testing"; $xyz = 3.14; $foo = $foo + 1; ?> Operators Arithmetic, Assignment, Bitwise, Comparison Error control, Execution, Incr/Decr, Logical
Basics – Arrays Arrays <?php $foo[1] = 1; $foo[2] = 2; $bar[1][2] = 3; ?>
Basics – Functions Functions & calling them phpinfo(); foo(); $len = strlen($foo);
Basics – Control Structures for, while, do – while <?php while($foo) { ... } ?>
Basics – Output, Comments echo, printf() <?php echo $foo; printf(".2f",$price); ?> Comments // Single line comments /* Multi line comments */
Form Handling with PHP - I Form Code <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 in Browser
Form Handling with PHP – II Processing PHP Script Hi <?echo $name?>. You are <?echo $age?> years old. Output in browser Register Globals Off Hi <?echo $_POST['name'] ?>. You are <?echo $_POST['age'] ?> years old.
Language Syntax PHP is mixture of C, Perl & HTML 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; } }
Basic Data types - I Numbers (integer and real) Strings Dynamic typing $a = 1234; $b = 1.25; $c = 'Hello'; $d = “$c World”; $e = 10 + 1.5; echo "$a - $b - $c - $d"; // 1234 - 1.25 - Hello - Hello World - 6.5
Basic Data types – II Booleans $status = true; if ($status) { $status = false; } Ordered and Associative $a[0] = 1; $a[1] = "foo"; $a[] = 1.57; $catch_it['cat'] = "mouse"; $catch_it['dog'] = "cat";
User Defined Functions Pass by value / reference Default values function calc ($op1, &$op2, $debug=true) { $val = $op1 + $op2; if ($debug) echo "$op1 + $op2 = $val<br/>\n”; return $val; } $operand1 = 3; $operand2 = 2; echo calc ($operand1, $operand2);
Object Oriented PHP Workable OO support, mature in PHP5 Classes, objects, inheritance,$this class Cart { var $items; var $id; function Cart() { $this->id = uniqid(); } function add_item($prodID, $num) { $this->items[$prodID] += $num; } } $cart = new Cart; $cart->add_item(1, 3); // add 3 qty of product 1
Date / Time Functions Unix Epoch time date(), time(), mktime() <?php echo date("M d, Y H:i:s", time()); ?> Feb 15, 2003 12:25:45 Many complex calculations possible
String Manipulation Lot of functions – strlen, substr, trim, strstr, str_replace, strtolower ... Regular Expressions – ereg, preg String Tokens – explode, implode, strtok $a = explode(":", "This:string:has:delimiters."); while (list(,$value) = each($a)) { if (strcmp($value, "has") == 0) { echo "had "; } else echo $value." "; } // This string had delimiters.
File Operations fopen, fclose, fread, fwrite (like C) file, read_file, file_get_contents Possible to open HTTP and FTP URLs <?php $file = "sample.txt"; $fp = fopen($file, "r"); $contents = fread($fp, filesize($file); fclose($fp); ?>
Variable Scope Default file scope, local in functions Global scope in functions GLOBAL $var; Static variables Static $var; System Global variables _POST, _GET, _COOKIE, _SESSION, _REQUEST, _SERVER, _ENV, _FILES
Guest Book application – I <html><head><title>My Guestbook</title></head> <body> <h1>Welcome to my Guestbook</h1> <h2>Please write me a little note below</h2> <form action="<?="$PHP_SELF"?>" method="POST"> <textarea cols=40 rows=5 name=note wrap=virtual></textarea> <input type=submit value=" Send it "> </form> <?if(isset($note)) { $fp = fopen("/tmp/notes.txt","a"); fputs($fp,nl2br($note.'<hr>').'<br>'); fclose($fp); } ?><h2>The entries so far:</h2> <? @ReadFile("/tmp/notes.txt") ?> </body></html>
SQL Example Typical DB interaction mysql_pconnect("db.server.com","username","password"); mysql_select_db("products"); $result = mysql_query("SELECT * FROM details"); if ($result && mysql_num_rows($result)) { echo "<TABLE>\n"; echo "<TR><TH>Name</TH> <TH>Description</TH></TR>\n"; while ($a = mysql_fetch_array($result)) { echo "<TR><TD>$a[name]</TD> <TD>$a[descr]</TD></TR>"; } echo "</TABLE>"; } else { echo "<P>Nothing in here!"; } Supports almost all DBs IBM DB2, Informix, Ingres, MS-SQL, MySQL, ODBC, Oracle, PostgreSQL, Sybase,dBase, FilePro, dbm...
Guest Book on steroids <html><head><title>My Guestbook</title></head> <body><h2>Please write me a little note below</h2> <form action="<? echo "$PHP_SELF#results"?>" method="POST"> <textarea cols=40 rows=5 name="note" wrap=virtual></textarea> <input type="submit" value=" Send it "></form> <? mysql_connect('localhost', 'user', 'pass'); mysql_select_db('database'); if(isset($note)) { $ts = date("Y-m-d H:i:s"); mysql_query("insert into comments (ID, note, ts) values (0,'$note','$ts')"); } ?> <h2>The entries so far:</h2> <? $result = mysql_query("select * from comments"); while($row=mysql_fetch_row($result)) { echo $row[0] ." " . $row[1] . " " . $row[2] ."<br>\n"; } ?> </body></html>
DB Abstraction PEAR DB Class <?php require_once 'DB.php'; $db = DB::connect('odbc://user:pw@host/db'); $stmt = $db->prepare('SELECT * FROM comments'); $result = $db->execute($stmt); while($row = $db->fetchrow($result)) { while($row as $field => $value ) { echo "$field: $value<br>\n"; } } $db->disconnect(); ?>
Headers & Cookies Header Header('Location: http://www.php.net'); SetCookie SetCookie('name', 'value'); echo $HTTP_COOKIE_VARS['name']; Headers must be sent before content
Sessions PHPSESSID Using sessions session_start(); session_register(“variable”); $_SESSION['name'] = $value; echo $_SESSION['name']; session_destroy();
Image Generation GD Library <? Header("Content-type: image/png"); $im = ImageCreate(630,80); $blue = ImageColorAllocate($im,0x5B,0x69,0xA6); $white = ImageColorAllocate($im,255,255,255); $black = ImageColorAllocate($im,0,0,0); ImageTTFText($im, 45, 0, 10, 57, $black, "CANDY", $text); ImageTTFText($im, 45, 0, 6, 54, $white, "CANDY", $text); ImagePNG($im); ?> <IMG src="txt.php?text=<?=urlencode($text);?>">
What more can PHP do? PDF Generation
What more can PHP do? Smarty templates Separation of logic and layout Templates It's own language Caching
Smarty Example – tpl file <html><head><title>My Guestbook </title></head><body><h1>Welcome to my Guestbook</h1><h2>Please write me a little note below</h2><form action="{$SCRIPT_NAME}" method="POST"><textarea cols=40 rows=5 name="note" wrap=virtual></textarea><input type="submit" value="Send it"></form><h2>The entries so far:</h2> {section name=msgs loop=$notes} {$notes[msgs].id} {$notes[msgs].ts} {$notes[msgs].comment}<br>{/section}</body></html>
Smarty Example – PHP file <?phprequire('Smarty.class.php');$smarty = new Smarty;$smarty->debugging = true;mysql_connect('localhost','user','pass');mysql_select_db('database');/* insert new note */if(isset($note)) { $ts = date("Y-m-d H:i:s"); mysql_query("insert into comments values (0,'$note','$ts')");}/* read existing notes */$result = mysql_query('select * from comments');if(!$result) echo mysql_error();while($notes[]=mysql_fetch_array($result,MYSQL_ASSOC));$smarty->assign('notes',$notes);$smarty->display("guestbook.tpl");?>
What more can PHP do? LDAP SNMP IMAP (POP, NNTP) FTP Flash XML parser / XSLT DCOM (Win32 only) Java Connectivity • Curl • zlib (compressed IO) • Charset conversion • ASPELL/PSPELL • MCRYPT • WDDX • Ncurses • 100 extensions!
Latest Developments PEAR and PECL SOAP Zend Engine 2 New Object model Unified Constructors and Destructors Objects are references Exceptions