1 / 98

PHP

PHP . Dynamic Web programming. PHP - history. PHP is a language for creating interactive web sites.  It was originally called "Personal Home Page Tools"  when it was created in 1994 by Rasmus Lerdorf to keep  track of who was looking at his online resume .

rudolf
Download Presentation

PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Dynamic Web programming

  2. PHP - history • PHP is a language for creating interactive web sites.  • It was originally called "Personal Home Page Tools" when it was created in 1994 by RasmusLerdorf to keep track of who was looking at his online resume. • Mid-1997: Students AndiGutmans and ZeevSuraskiredesigned the PHP language engine and wrote some of the most popular PHP modules.  • At that time PHP already had its own site, php.net, run by the computer science community, and was powering thousands of Web sites. • The script was just beginning to be recognized by developers who preferred the multi-platform script over its more limited Microsoft ASP counterpart that interfaces only with Windows NT.  • Today PHP Web developers applaud the script's simplicity, flexibility, and ability to generate HTML pages quickly. Over 5,100,000 (1/2001) sites around the world use PHP. 

  3. What is PHP? • PHP is a server-side scripting language, like ASP • PHP scripts are executed on the server • PHP supports many databases (MySQL, Informix, • Oracle etc.) • PHP is open source and free to download • PHP files many contain text, HTML tags and scripts • PHP files are returned to the browser as plain HTML • PHP files have extension of “.php”, “.php3” or • “.phtml”

  4. Why PHP? • PHP runs on different platforms (windows, Linux etc) • PHP is compatible with almost all servers used • today (Apache, IIS etc) • PHP is FREE to download from official PHP resource: • http://www.php.net • PHP is easy to learn and runs efficiently on the • server side

  5. PHP vs ASP • Php - Open source  asp - not • Php - Very fast !!!  Asp - ?? • Php - Superior Memory Management • Asp - windows memory management  • Php - No Hidden Costs with PHP • asp - (Need encryption - buy ASPEncrypt. Need email management - buy ServerObject'sQMail. Need file uploading - buy Software Artisans SA-FileUp. 

  6. PHP vs ASP • The following databases are currently supported: Adabas D Ingres Oracle (OCI7 and OCI8) dBase InterBaseOvrimosEmpress FrontBasePostgreSQLFilePro (read-only) mSQL Solid Hyperwave Direct MS-SQL Sybase IBM DB2 MySQLVelocis

  7. PHP vs ASP • Php-> HTTP GET and POST variables are automatically created as global variables (security??) asp->i have to "Request." my HTTP GET and POST variables??  • Php-> if your phpscript is not working , you can blame no one but yourself asp-> You can blame Micro$oft, iis , asp and so on...  • Php-> you don't have time for a coffie break because your computer never crashes asp-> you have a lot of coffie breaks ... 

  8. What you need for PHP? • Install an Apache Server (web server) on a windows or • Linux machine • Install PHP (server side scripting technology) on a • windows or Linux machine • Install MySQL (database server) on a windows or Linux • machine And lots of Configuration work!!! • Alternatively, Just download WAMP Server and install • It will not only installs Apache, MySQL and PHP on windows • machine but will also configure these software. • Provides you an easy to access interface to run and host • PHP files.

  9. PHP is C++ Style • PHP is very similar to C++. • As a consequence if you know java (also a c++ clone), C++ or • indeed almost any other computer science language you pretty • much already know PHP. • However more than anything PHP is based on Perl. • PHP is an Embedded Script • You could view PHP as an embedded language. • However it is very much still a Server Side Language – this is not the same sort of thing as Javascript

  10. Creating a PHP program • You can use any text editor. (Notepad,Dreamweaver) • Different Web server setups work in different ways. (we will • use XAMPPServer that bundles Apache, MySQL, PHP) • Create a new file in Dreamweaver and save it with .php • extension. • Use <?phpTo open your code and ?> to close it. • Anything not in those tags is rendered as HTML. • Type your code and load it up in a web browser. • Any webpage that use even a single line of php and all other • contents are in HTML must be saved with .php extension. • Otherwise phpcode will not run.

  11. PHP Tag Styles • XML Style: • <?php • print “this is XML style”; • ?> • Short Style: • <? • print “this is ASP style”; • ?> • To use Short style, the PHP you are using must have “short tags” enabled in its configfile… this is almost always the case.

  12. Hello, PHP ! • simple output : ("CGI Style")  • <? echo "<html><head></head><body>Hello world! • <br></body></html>"; ?>  • simple output 2 : (embeded style)  • <html> <head></head> <body> <?print "Hello world!" ?><br> </body>  • More ways of Escaping from HTML : PHP3 style:  • <?phpecho "Hello world!";  ?> 

  13. Hello, PHP ! • the "<script>" tag:  • <script language="php">  echo "Hello world!"; </script>  • ASP style ():  • <% echo "hello world"; %> 

  14. /*PHP Comments*/ • <? //comment # comment /* multi line comment (c++ style) */ ?> 

  15. PHP is for Lazy People • Basic data types • Scalar • numbers (integers and float. Holds 4 bytes of space) • strings (Double-quoted "abc“ and single-quoted 'abc' ) • booleans(true, false ) • Compound • Arrays • Objects • Dynamic typing • Don't have to declare types • Automatic conversion done

  16. PHP $Variables • Every variable must have a $ sign at the beginning of the variable. • <? • $x = false; // boolean • $x = true; • $x = 10; // decimal • $x = 1.45; // Floating point • $x = ’Hello World’; // Hello World • $x = "mmm\"oo'oo"; // mmm"oo'oo • $y = &$x; // Reference • $x[1] = 10; // array of decimals • $x["name"] = “jimbo"; // associative array • $x[2]["lala"] = "xx"; // a two dimensional array • ?>

  17. Variable substitution • Variable substitution provides a convenient way to embed data held in a variable directly into string literals. • PHP examines, or parses , double-quoted strings and replaces variable names with the variable's value. • The following example shows how: • <? • $number = 45; • $vehicle = "bus"; • $message = "This $vehicle holds $number people"; • // prints "This bus holds 45 people" • print $message; • ?>

  18. PHP $Variables • Type Juggling :  • <? $x = "100"; $x++; // $x is now 101 ?>  • Variable variables: (@#%^!!)  • <? $moo = "xxx"; $a = "moo"; $$a = "boo"; echo "variable \$a is '$a' and \$moo is '$moo'.<br>"; // will output: variable $a is 'moo' and $moo is 'boo'; ?> 

  19. Constants • Constants associate a name with a scalar value. • For example, the Boolean values true and false are constants associated with the values 1 and 0, respectively. • It's also common to declare constants in a script. • Consider this example constant declaration: • <? • define("PI", 3.14159); • // This outputs 3.14159 • print PI; • ?>

  20. Type conversion • Conversion between types can be pure (forced) or dirty (automatic)… • Forced casting (pure): • <? • $bool = true ; • print (int)$bool ; • ?> • Automatic Type Juggling (dirty): • <? $x = "100"; • $x++; // $x is now 101 • ?> • Check Point: • If $x = "12" and $y = "13" What will be the output for $x . $y and $x + $y?

  21. Variable Scope • The 3 basic types of scope in PHP is: • Global variables declared in a script are visible throughout that script, but not inside functions • Declared as: global $x; • Variables used inside functions are local (limited) to the function • By default a variable inside a function is local. • You can also define a local variable as: local $x; • Variables used inside functions that are declared as globalrefer to the global variable of the same name

  22. Operators • + Addition - Subtraction * Multiplication / Division % Modulus & And | Or ^ Xor. add string (like in perl) << Shift left >> Shift right 

  23. Assignment Operators • <? $x = "Hello "; $x.= "wrold!"; $x = 10; $x++; $x *= 5; $x = array(1,3,2,4,10); $x = array(      "a" => "4",      "i" => "1",      "e" => "3",      "later"  => "l8r" ); ?> 

  24. Comparison Operators • $a == $b Equal - True if $a is equal to $b.  • $a === $b Identical - True if $a is equal to $b, and they are of the same type.  • $a != $b Not equal - True if $a is not equal to $b.  • $a !== $b Not identical - True if $a is not equal to $b, or they are not of the same type.  • $a < $b Less than - True if $a is strictly less than $b.  • $a > $b Greater than - True if $a is strictly greater than $b.  • $a <= $b Less than or equal to - True if $a is less than or equal to $b.  • $a >= $b Greater than or equal to - True if $a is greater than or equal to $b. 

  25. Comparison Operators • the ? operator - like the C operator:  • <?echo ($x==0) ? "X value is zero" : "X value is not zero"; ?> 

  26. Logical Operators • $a and $b True if both $a and $b are true.  • $a or $b True if either $a or $b is true.  • $a xor $b True if either $a or $b is true, but not both.  • ! $a True if $a is not true.  • $a && $b True if both $a and $b are true.  • $a || $b True if either $a or $b is true. 

  27. Simple String functions • chr - Return a specific character • ord - Return ASCII value of character • strlen - Get string length • strpos - Find position of first occurrence of a string • strrev - Reverse a string • strtolower - Make a string lowercase • strtoupper - Make a string uppercase • str_replace - Replace all occurrences of the search string with the replacement string

  28. Control Structures • if:  • <? if ($a > $b) {     print "a is bigger than b";     $b = $a; } ?>  • else: • <? if ($a > $b) {     print "a is bigger than b"; } else {     print "a is NOT bigger than b"; } ?> 

  29. Control Structures • elseif:  • <? if ($a > $b) {     print "a is bigger than b"; } elseif ($a == $b) {     print "a is equal to b"; } else {     print "a is smaller than b"; } ?> 

  30. While loops • While:  • <? $i = 1; while ($i <= 10) {     print $i++;  /* the printed value would be                     $i before the increment                     (post-increment) */ } ?>  • do .. while:  • <? $i = 0; do {    print $i++; } while ($i< 10); ?> 

  31. For loops • <? /* example 1 */ for ($i = 1; $i <= 10; $i++) {     print $i; } /* example 2 */ for ($i = 1;;$i++) {     if ($i > 10) {         break;     }     print $i; } 

  32. foreachloops • <? /* values */ $a = array (1, 2, 3, 17); foreach ($a as $v) {    print "Current value of \$v: $v.<br>"; } /* values and keys */ $a = array (1, 2, 3, 17); foreach($a as $k => $v) {     print "\$a[$k] is $v<br>"; } ?> 

  33. switch • <? switch ($i) {     case 0:         print "i equals 0";         break;     case 1:         print "i equals 1";         break;     case 2:         print "i equals 2";         break;     default:         print "i is not equal to 0, 1 or 2"; } ?> 

  34. includes • <? include("/libs/mylib1.inc"); include_once("/libs/mylib2.inc"); ?> 

  35. Predefined variables • <? $x = $SERVER_NAME; #The name of the server host  $x = $REQUEST_METHOD; #'GET', 'HEAD', 'POST' or 'PUT' $x = $PHP_SELF; #The filename of the currently executing script $x = $HTTP_COOKIE_VARS["Varname"]; $x = $HTTP_GET_VARS["Varname"]; $x = $HTTP_POST_VARS["Varname"]; # variables that were posted using post, get or cookie. $x = $REMOTE_ADDR;  # The IP address from which the user is viewing the current page.  ?> 

  36. functions • <? function la(){      return "lalala\n<br>"; }  echo la(); // will output lalala?> 

  37. functions • Variable scope:  • <?$x = "XXX"; functionput_in_x($myparam){      $x = $myparam; }  put_in_x("YYY"); echo $x; // will output XXX ?> 

  38. functions • using global variables in a function.  • <?$x = "XXX"; function put_in_x($myparam){      global $x;     $x = $myparam; }  put_in_x("YYY"); echo $x; // will output YYY ?> 

  39. variables functions • (partial list) empty - Determine whether a variable is set isset - same as !empty($a) gettype - Get the type of a variable get_defined_vars- Returns an array of all defined variables is_array- Finds whether a variable is an array is_bool- Finds out whether a variable is a booleanis_float - Finds whether a variable is a float is_int - Find whether a variable is an integer is_null - Finds whether a variable is NULL is_numeric- Finds whether a variable is a number or a numeric string is_object- Finds whether a variable is an object is_string - Finds whether a variable is a string unset - Unset a given variable  • functions for debugging : print_r- Prints human-readable information about a variable var_dump - Dumps information about a variable 

  40. string functions • (partial list) chop - Strip whitespace from the end of a string chr - Return a specific character crypt - DES-encrypt a string hebrev - Convert logical Hebrew text to visual text htmlspecialchars - Convert special characters to HTML entities md5 - Calculate the md5 hash of a string nl2br - Inserts HTML line breaks before all newlines in a string ord - Return ASCII value of character sprintf- Return a formatted string strip_tags- Strip HTML and PHP tags from a string addslashes - Quote string with slashes stripslashes - Un-quote string quoted with addslashes() 

  41. string functions • strlen- Get string length strpos - Find position of first occurrence of a string strrev- Reverse a string strtolower - Make a string lowercase strtoupper - Make a string uppercase str_replace - Replace all occurrences of the search string with the replacement string join - Join array elements with a string split - split string into array by regular expression  • <? $date = "04/30/1973";  // Delimiters may be slash, dot, or hyphen list ($month, $day, $year) = split ('[/.-]', $date); echo "Month: $month; Day: $day; Year: $year<br>\n"; ?> 

  42. array functions • (partial list) count - Count elements in a variable array_pop - Pop the element off the end of array array_push - Push one or more elements onto the end of array array_reverse - Return an array with elements in reverse order array_shift - Shift an element off the beginning of array array_unshift - Prepend one or more elements to the beginning of array array_sum - Calculate the sum of values in an array. array_unique- Removes duplicate values from an array array_values- Return all the values of an array in_array - Return TRUE if a value exists in an array array_search- Searches the array for a given value and returns the corresponding key if successful sizeof - Get the number of elements in variable sort - Sort an array uksort - Sort an array by keys using a user-defined comparison function usort - Sort an array by values using a user-defined comparison function 

  43. array functions • <? function cmp ($a, $b) {        if ($a == $b) return 0;     return ($a < $b) ? -1 : 1; } $a = array (3, 2, 5, 6, 1); usort ($a, "cmp"); ?>  • array_flip- Flip all the values of an array  • <? $trans = array ("a" => 1, "b" => 1, "c" => 2); $trans = array_flip ($trans); // now $trans is : array(1 => "b", 2 => "c"); ?> 

  44. Object oriented • <?php// base class with member properties and methods class Vegetable { var $edible; var $color;     function Vegetable( $edible, $color="green" ) {         $this->edible = $edible;         $this->color = $color;     }     function is_edible() {         return $this->edible;     }     function what_color() {         return $this->color;     }  • } // end of class Vegetable • // extends the base class class Spinach extends Vegetable {     var $cooked = false;     function Spinach() {     $this->Vegetable ( true, "green" );     }     function cook_it() {         $this->cooked = true;     }     function is_cooked() {         return $this->cooked;     }    } // end of class Spinach $veggie = new Vegetable(true,"blue"); $leafy = new Spinach(); ?> 

  45. HTML Forms • the form.php (or form.html): • <form action="receive.php" method="post"> • Name: <input type="text" name="username"><br> • <input type="submit"> • </form> • recv.php- the file that will receive the data:  • <? • $username = $_POST[“username”]; • if($username) • print "your name is $username <br>"; • else • { • ?> • <a href="form.php">please fill the form!</a> • <? • } • ?>

  46. "All in one" Form • same in one file (PHP style):  • <? • $username = $_POST[“username”]; • if($username) • { • echo "your name is $username !!! <br>"; • } • else • { • ?> • <form action="<?= $PHP_SELF ?>" method="post"> • Name: <input type="text" name="username"><br> • <input type="submit"> • </form> • <? • } • ?>

  47. Trimming Strings • trim() strips whitespace from the start and end of a string and returns the result. • It also gets rid of new lines, tabs, carriage returns • and the like. • ltrim() and chop() do similar things – but only from one end of the string.

  48. Changing Case • Most people who use your sites will be Muppets. (although • your sites will probably only be viewed by members of staff so • draw your own conclusions). • Whatever you tell them to do, they won’t enter data in the • format you want and this will matter. Login names are • classic examples of this. • Imagine someone types “aStOnVillA” into a field… • Strtoupper() Turns string to uppercase ASTON VILLA • Strtolower()Turns string to lowercase aston villa • Ucfirst()Capitalisesfirst character Aston villa • Ucwords()Capitalises every word Aston Villa

  49. Adding Slashes • To do this escaping normally you just add a \ (backslash). • This can be very painful to do manually. • AddSlashes() a function to do it for you. • StripSlashes() reverses the process. • So if a user typed in: You said to me that “you don’t give gaurantees” • $userInput = AddSlashes($userInput) • You said to me that /“you don/’t give gaurantees/”.

  50. Exploding Strings • explode() returns an array of strings created by breaking the subject string at each occurrence of the separator string. • Syntax: explode(sep, subject); • $email = falak.nawaz@seecs.edu.pk”; • $arr = explode(“@”, $email); $arr[0] = “falak.nawaz” $arr[1] = “seecs.edu.pk” • $domains = explode(“.”, $arr[1]); $domain[0] = “seecs” $domain[1] = “edu” $domain[2] = “pk” • Implode() reverses the process.

More Related