Published on


Published in: Education, Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. ITCS 323 Web Programming Concepts III
  3. 3. What is PHP? recursive acronym for PHP: Hypertext Preprocessor a widely-used open source general-purpose scripting language
  4. 4. What is PHP? especially suited for web development and can be embedded into HTML is a server-side scripting language scripts are executed on the server supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC
  5. 5. What is PHP? PHP files can contain text, HTML tags and scripts  PHP pages contain HTML with embedded code that does "something" have a file extension of ".php", ".php3", or ".phtml“ enclosed in special start and end processing instructions <?php and ?>  allow you to jump into and out of "PHP mode."
  6. 6. Example • <!DOCTYPE HTML PUBLIC <html> <head> <title>Example</title> </head> <body> <?php echo “Hello World!"; ?> </body> </html>
  7. 7. Why PHP? open source software free to download and use runs on different platforms (Windows, Linux, Unix, Mac OS X, RISC OS, etc.) compatible with almost all servers used today (Apache, IIS, etc.) support for a wide range of databases with PHP, you have the freedom of choosing an operating system and a web server
  8. 8. Why PHP? not limited to output HTML  PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly  can autogenerate files, and save them in the file system
  9. 9. Why PHP? 1. Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". • <html> <head> <title>Example</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?>
  10. 10. Why PHP? 2. Cross Platform Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases  Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003  Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm
  11. 11. Why PHP? 3. Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free. PHP Software Free Platform Free (Linux) Development Tools Free PHP Coder, jEdit
  12. 12. Difference? Compare to other client-side program like java script. PHP code is executed on the server PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform) It is an open source
  13. 13. Three main areas where PHP scripts are used. 1. Server-side scripting. 2. Command line scripting. 3. Writing desktop applications.
  14. 14. Three main areas where PHP scripts are used. 1. Server-side scripting.  most traditional and main target field for PHP  three things to make this work 1. PHP parser (CGI or server module) 2. web server 3. web browser
  15. 15. Three main areas where PHP scripts are used. 2. Command line scripting  run PHP script without any server or browser  only need the PHP parser to use  this type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows).  These scripts can also be used for simple text processing tasks
  16. 16. Three main areas where PHP scripts are used. 3. Writing desktop applications.  One of the advance features of PHP  have the ability to write cross-platform applications  PHP-GTK is an extension to PHP  not available in the main distribution
  17. 17. What is needed? Web sever that support php (apache server) Sql database (MySql) PHP installer
  18. 18. Assignment • How to install, configure and use php • Give different AMP packages • Give different php functions, give example code and syntax
  19. 19. Overview to PHP BRIEF HISTORY
  20. 20. Brief History PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix. PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc. PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans . PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added. PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP
  21. 21. As of August 2004, PHP is used on 16,946,328 Domains, 1,348,793 IP Addresses This is roughly 32% of all domains on the web.
  22. 22. Introduction PHP START UP
  23. 23. Objectives PHP Structure Variables, operators, and Comments PHP Arrays Passing Variables in Links HTML special Characters Passing Variables in Forms
  24. 24. Installation Procedure 1. install your selected HTTP (web) server on your system, and make sure that it works. 2. Run the executable installer and follow the instructions provided by the installation wizard.  Two types of installation are supported – 1. standard, which provides sensible defaults for all the settings it can, 2. advanced, which asks questions as it goes along.
  25. 25. Installation Procedure 3. The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually. 4. Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.
  26. 26. PHP Script • Typically file ends in .php--this is set by the web server configuration • Separated in files with the <?php ?> tag • php commands can make up an entire file, or can be contained in html--this is a choice…. • Program lines end in ";" or you get an error • Server recognizes embedded script and executes • Result is passed to browser, source isn't visible <P> <?php $myvar = "Hello World!"; echo $myvar; ?> </P>
  27. 27. Two ways • You can embed sections of php inside html: <BODY> <P> <?php $myvar = "Hello World!"; echo $myvar; </BODY> • Or you can call html from php: <?php echo "<html><head><title>Howdy</title> … ?>
  28. 28. Variables • Typed by context (but one can force type), so it's loose • Begin with "$" (unlike javascript!) • Assigned by value – $foo = "Bob"; $bar = $foo; • Assigned by reference, this links vars – $bar = &$foo; • Some are preassigned, server and env vars – For example, there are PHP vars, eg. PHP_SELF, HTTP_GET_VARS
  29. 29. Variables • Case-sensitive ($Foo != $foo != $fOo) • Global and locally-scoped variables – Global variables can be used anywhere – Local variables restricted to a function or class • Certain variable names reserved by PHP – Form variables ($_POST, $_GET) – Server variables ($_SERVER) – Etc.
  30. 30. Variable of variable • Using the value of a variable as the name of a second variable) $a = "hello"; $$a = "world"; • Thus: echo "$a ${$a}"; • Is the same as: echo "$a $hello"; • But $$a echoes as "$hello"….
  31. 31. Variable usage <?php $foo = 25; $bar = “Hello”; $foo = ($foo * 7); $bar = ($bar * 7); ?> // Numerical variable // String variable // Multiplies foo by 7 // Invalid expression
  32. 32. Constant • You cannot alter the value of constant after declaration – -define(CONSTANT, “value”); – -print CONSTANT;
  33. 33. Magic Constants • PHP has lot of predefined variables • Also, predefined Constants: – _LINE_ – _FILE_ – _FUNCTION_ – _CLASS_ – _METHOD_
  34. 34. Echo • The PHP command ‘echo’ is used to output the parameters passed to it – The typical usage for this is to send data to the client’s web-browser • Syntax – void echo (string arg1 [, string argn...]) – In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function
  35. 35. Echo Example <?php $foo = 25; $bar = “Hello”; echo echo echo echo echo ?> $bar; $foo,$bar; “5x5=”,$foo; “5x5=$foo”; ‘5x5=$foo’; // Numerical variable // String variable // // // // // Outputs Outputs Outputs Outputs Outputs Hello 25Hello 5x5=25 5x5=25 5x5=$foo • Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25 • Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP • This is true for both variables and character escape-sequences (such as “n” or “”)
  36. 36. Concatenation • Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; Print $string3; ?> Hello PHP
  37. 37. Escaping the Characters • If the string has a set of double quotation marks that must remain visible, use the [backslash] before the quotation marks to ignore and display them. <?php $heading=“”Computer Science””; Print $heading; ?> “Computer Science”
  38. 38. Date Display 2009/4/1 Wednesday, April 1, 2009 $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is April 1st, 2009 # It would display as 2009/4/1 $datedisplay=date(“l, F d, Y”); Print $datedisplay; # If the date is April 1st, 2009 # Wednesday, April 1, 2009
  39. 39. Month, Day, Date Format Symbol M F m n Day of Month Day of Month Day of Week Day of Week Jan January 01 1 d J l D 01 1 Monday Mon
  40. 40. PHPinfo() • The phpinfo() function shows the php environment • Use this to read system and server variables, setting stored in php.ini, versions, and modules • Notice that many of these data are in arrays • This is the first script you should write…
  41. 41. Operator • Arithmetic (+, -, *, /, %) and String (.) • Assignment (=) and combined assignment $a $a $b $b = 3; += 5; // sets $a to 8; = "Hello "; .= "There!"; // sets $b to "Hello There!"; • Bitwise (&, |, ^, ~, <<, >>) – $a ^ $b(Xor: Bits that are set in $a or $b but not both are set.) – ~ $a (Not: Bits that are set in $a are not set, and vice versa.) • Comparison (==, ===, !=, !==, <, >, <=, >=)
  42. 42. Arithmetic Operation <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “<p><h1>$total</h1>”; // total is 45 ?> • • • • $a - $b $a * $b $a / $b $a += 5 // subtraction // multiplication // division // $a = $a+5 Also works for *= and /=
  43. 43. Coercion • Just like javascript, php is loosely typed • Coercion occurs the same way • If you concatenate a number and string, the number becomes a string
  44. 44. Operators • Error Control (@) – When this precedes a command, errors generated are ignored (allows custom messages) • Execution (` is similar to the shell_exec() function) – You can pass a string to the shell for execution: $output = `ls -al`; $output = shell_exec("ls -al"); – This is one reason to be careful about user set variables! • Incrementing/Decrementing ++$a (Increments by one, then returns $a.) $a++ (Returns $a, then increments $a by one.) --$a (Decrements $a by one, then returns $a.) $a-- (Returns $a, then decrements $a by one.)
  45. 45. Operators • Logical $a and $b $a or $b $a xor $b And Or Xor ! $a $a && $b $a || $b Not And Or True if True if True if but not True if True if True if both $a and $b are either $a or $b is either $a or $b is both. $a is not true. both $a and $b are either $a or $b is true. true. true, true. true. • The two ands and ors have different precedence rules, "and" and "or" are lower precedence than "&&" and "||" • Use parentheses to resolve precedence problems or just to be clearer
  46. 46. Control Structure • Wide Variety available – if, else, elseif – while, do-while – for, foreach – break, continue, switch – require, include, require_once, include_once Mostly parallel to what we've covered already in javascript if, elseif, else, while, for, foreach, break and continue
  47. 47. Control Structure  Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script.  Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops).  Example if/else if/else statement: if ($foo == 0) { echo ‘The variable foo is equal to 0’; } else if (($foo > 0) && ($foo <= 5)) { echo ‘The variable foo is between 1 and 5’; } else { echo ‘The variable foo is equal to ‘.$foo; }
  48. 48. If….Else • If (condition) { Statements; } Else { Statement; } <?php If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?>
  49. 49. Alternative Syntax • Applies to if, while, for, foreach, and switch • Change the opening brace to a colon • Change the closing brace to an endxxx <?php statement <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> if ($a == 5): echo "a equals 5"; echo "..."; else: echo "a is not 5"; endif; ?>
  50. 50. While…loop • While (condition) { Statements; } <?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ?> hello PHP. hello PHP. hello PHP.
  51. 51. Switch • Switch, which we've seen, is very useful • These two do the same things…. switch ($i) { if ($i == 0) { echo "i equals 0"; } elseif ($i == 1) { echo "i equals 1"; } elseif ($i == 2) { echo "i equals 2"; } case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; }
  52. 52. Function • Functions MUST be defined before then can be called • Function headers are of the format function functionName($arg_1, specified – Note that no return type is $arg_2, …, $arg_n) • Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
  53. 53. Function Example <?php // This is a function function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2; return $arg_2; } $result_1 = foo(12, 3); echo $result_1; echo foo(12, 3); ?> // Store the function // Outputs 36 // Outputs 36
  54. 54. Include Files Include “opendb.php”; Include “closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: <hr SIZE=11 NOSHADE WIDTH=“100%”> <i>Copyright © 2008-2010 KSU </i></font><br> <i>ALL RIGHTS RESERVED</i></font><br> <i>URL:</i></font><br>
  55. 55. Scope <?php $a = “Pekka”; Print “My Name is “. $a; ?> <?php $a = “Pekka”; Function test() { Print $a; } Print “My Name is “; Test(); ?>
  56. 56. Scope <?php $a = “Pekka”; Function test() { global $a; Print $a; } Print “My Name is “; Test(); ?>
  57. 57. PHP BASIC
  58. 58. Strings
  59. 59. My First PHP script PHP FORMS AND SESSION
  60. 60. PHP Forms •Access to the HTTP POST and GET data is simple in PHP •The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form>
  61. 61. Why PHP Sessions? Whenever you want to create a website that allows you to store and display information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features. Cookies are about 30% unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there. PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99% flawless in operation and it is virtually invisible to the user.
  62. 62. PHP Sessions •Sessions store their identifier in a cookie in the client’s browser •Every page that uses session data must be proceeded by the session_start() function •Session variables are then set and retrieved by accessing the global $_SESSION[] •Save it as session.php <?php session_start(); if (!$_SESSION["count"]) $_SESSION["count"] = 0; if ($_GET["count"] == "yes") $_SESSION["count"] = $_SESSION["count"] + 1; echo "<h1>".$_SESSION["count"]."</h1>"; ?> <a href="session.php?count=yes">Click here to count</a>
  63. 63. Avoid Error PHP Sessions PHP Example: <?php echo "Look at this nasty error below:<br />"; session_start(); ?> Error! Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 PHP Example: <?php session_start(); echo "Look at this nasty error below:"; ?> Correct
  64. 64. Destroy PHP Sessions Destroying a Session why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Well, imagine that you had a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called session_destroy() comes in handy. session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session. NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy. Here's how we use session_destroy():
  65. 65. Destroy PHP Sessions <?php // start the session session_start(); header("Cache-control: private"); //IE 6 Fix $_SESSION = array(); session_destroy(); echo "<strong>Step 5 - Destroy This Session </strong><br />"; if($_SESSION['name']){ echo "The session is still active"; } else { echo "Ok, the session is no longer active! <br />"; echo "<a href="page1.php"><< Go Back Step 1</a>"; } ?>
  66. 66. PHP Script • Save as sample.php: <!– sample.php --> <html><body> <strong>Hello World!</strong><br /> <?php echo “<h2>Hello, World</h2>”; ?> <?php $myvar = "Hello World"; echo $myvar; ?> </body></html>
  67. 67. Example – Show data into table • Function: list all tables in your database. Users can select one of tables, and show all contents in this table. • second.php • showtable.php
  68. 68. Example – Show data into table • second.php <html><head><title>MySQL Table Viewer</title></head><body> <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = ''; $dbuser = 'nruan'; $dbpass = ‘*****************’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database");
  69. 69. Example – Show data into table • second.php <html><head><title>MySQL Table Viewer</title></head><body> <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = ''; $dbuser = 'nruan'; $dbpass = ‘*****************’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database");
  70. 70. Example – Show data into table • Showtable.php <html><head> <title>MySQL Table Viewer</title> </head> <body> <?php $dbhost = ''; $dbuser = 'nruan'; $dbpass = ‘**********’; $dbname = 'nruan'; $table = $_POST[“table”]; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) die('Could not connect: ' . mysql_error()); if (!mysql_select_db($dbname)) die("Can't select database"); $result = mysql_query("SELECT * FROM {$table}"); if (!$result) die("Query to show fields from table failed!" . mysql_error());
  71. 71. Example – Show data into table • Showtable.php (cont) $fields_num = mysql_num_fields($result); echo "<h1>Table: {$table}</h1>"; echo "<table border='1'><tr>"; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); echo "<td><b>{$field->name}</b></td>"; } echo "</tr>n"; while($row = mysql_fetch_row($result)) { echo "<tr>"; // $row is array... foreach( .. ) puts every element // of $row to $cell variable foreach($row as $cell) echo "<td>$cell</td>"; echo "</tr>n"; } mysql_free_result($result); mysql_close($conn); ?> </body></html>
  72. 72. Function Covered • • • • mysql_connect() mysql_select_db() include() mysql_query() mysql_num_rows() mysql_fetch_array()mysql_close()