2. 02/21/12 Open Source Programming Introduction Unit – I Open source Programming PHP, Apache, MySQL, Postgress, SQL and Perl- Overview of PHP – Variables, operators, Constants, control structures arrays, Functions, classes – Handling files.
3. 02/21/12 By allowing the open exchange of information, programmers from all over the world contribute to make a truly powerful and efficient piece of software without royalties or fees. Open Source Programming What is Open source
4.
5.
6. 02/21/12 Apache — HTTP web server Tomcat web server — web container Mediawiki — wiki server software Alfresco, TYPO3 — content management system RenovatioCMS — content management system Joomla — content management system Drupal — content management system provides a collaborative environment for social networking sites, corporate Web sites, intranets, e-commerce applications and discussion sites. Open Source Programming OSP Software - Server
7. 02/21/12 WordPress — blog software MongoDB — document-oriented, non-relational database Moodle — course management system or virtual learning environment openSIS — open source Student Information System Open Source Programming OSP Software
8. 02/21/12 osCommerce — allows store owners to setup, run, and maintain online stores with minimum effort and with no costs P eaZip — File archiver Mozilla Firefox — web browser OpenOffice.org — office suite Stockfish — chess engine series, one of the strongest chess programs 7-Zip – File Archiver Open Source Programming OSP Software
9. 02/21/12 PHP — Hypertext Preprocessor Ruby,Tcl/Tk PERL & Python — Interpreted Dynamic Language MySQL — Data Base Open Source Programming OSP Software (Others)
16. 02/21/12 Open Source Programming AMP as Restaurant MySQL – This is Stockroom of ingredients.
17.
18. 02/21/12 GNU General Public License (GPL) GNU Library or "Lesser" General Public License (LGPL) MIT license (MIT) Mozilla Public License 2.0 (MPL-2.0) Common Development and Distribution License (CDDL-1.0) Eclipse Public License (EPL-1.0)
19.
20.
21.
22.
23.
24. 02/21/12 Open Source Programming CLIENT WEB SERVER HTTP Request (url) <HTML> <?php PHP code ?> </HTML> Gets Page <HTML> <B>Hello</B> </HTML> Interprets the PHP code Server response How it works? Browser creates the web page
25.
26.
27. 02/21/12 Open Source Programming PHP is denoted in the page with opening and closing tags as follows: <?php //php code ; ?> PHP Syntax
28. 02/21/12 <HTML> <HEAD> <TITLE> My First PHP Program </TITLE> <h1> </HEAD> <BODY> <?php echo “I’m a PHP Program.”; ?> </BODY> </HTML> Open Source Programming Code PHP Programs Result
29. 02/21/12 <?php $name=“VIT UNIVERSITY”; echo ‘My name is ‘,$name; ?> Open Source Programming Code PHP Programs Result
30.
31.
32.
33.
34.
35. 02/21/12 $MyStrVal = " This is an example of a string value "; $MyIntVal = 145665; // An integer value $MyBoolval = True; // A Boolean value can either be True or False $MyFloatVal=2346.45 // A float value $MyArrVal[0] = "My"; //A array containing three elements $MyArrVal[1] = "First"; $MyArrVal[2] = "Array"; Open Source Programming Variables (cont)
36. 02/21/12 Open Source Programming In PHP, Variable type can be changed by Settype Syntax: Settype(Variablename, “newDataType”); E.g. $pi = 3.14 //float Settype($pi,”string”); //now string – “3.14” Settype($pi,”integer”);// now integer - 3 Settype Settype
37. 02/21/12 Open Source Programming Syntax: Gettype(Variablename); E.g. $pi = 3.14; //float print gettype($pi); Print “---$pi <br>”; Settype($pi,”string”); print gettype($pi); Print “---$pi <br>”; Settype($pi,”integer”); print gettype($pi); Print “---$pi <br>”; In PHP, Variable type and can know by Gettype . Settype & Gettype
38.
39.
40. 02/21/12 Logical Operator Open Source Programming Operators (cont) Comparison Operator And Or ! Xor && ( high precedence) || ( high precedence) == != < > <= >= === (identical)
41.
42. 02/21/12 Open Source Programming 1. Echo & Print() is the common method in outputting data. Since it is a language construct, echo doesn’t require parenthesis like print(). 2. Output Text Usage: <?php echo “Hello World”; print(“Hello World”); // prints out Hello World ?> Output in PHP
43. 02/21/12 Open Source Programming 3. Output the value of a PHP variable: <?php echo $hits; // prints out the number of hits print ($hits); // returns a value if print process success. ?> 4. Can use “<br>” , to print in next line: <?php echo $a , “<br>”, $b ; // prints a & b in separate lines ?> Output in PHP
52. 02/21/12 Open Source Programming Array of arrays is called as multidimensional arrays. $Student = array ( "0"=> array ("name"=>"James", "sex"=>"Male", "age"=>"28"), "1"=> array ("name"=>"John", "sex"=>"Male", "age"=>"25"), "2"=> array ("name"=>"Susan", "sex"=>"Female", "age"=>"24")); $student[“1"][“name"] – returns John Multidimensional Arrays
53. 02/21/12 $u= array ( "0"=> array ("name"=>"James", "sex"=>"Male", "age"=>"28"), "1"=> array ("name"=>"John", "sex"=>"Male", "age"=>"25"), "2"=> array ("name"=>"Susan", "sex"=>"Female", "age"=>"24")); foreach ($u as $key=>$value) { echo "$key is $value"; echo "The actual user is $key.<br/>"; foreach ($value as $iKey => $iValue) { echo " ---> $iKey -> $iValue <br/>"; } } ?>
54. 02/21/12 Output : 0 is Array The actual user is 0. ---> name -> James ---> sex -> Male ---> age -> 28 1 is Array The actual user is 1. ---> name -> John ---> sex -> Male ---> age -> 25 2 is Array The actual user is 2. ---> name -> Susan ---> sex -> Female ---> age -> 24
56. 02/21/12 Functions: A function is a block of code that is not immediately executed but can be called by scripts whenever needs. Functions can be built-in or user-defined . They can require information to be passed to them and usually return a value. Open Source Programming Functions
57. 02/21/12 Open Source Programming <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r($a); ?> Array ( [a] => Dog [b] => Cat [c] => Horse ) Array( key=>value ) – Creates an array with keys and values Output: E.g.: Array Functions
58. 02/21/12 Open Source Programming array_chunk( array,size,preserve_key ) - splits an array into chunks of new arrays Array Functions
61. 02/21/12 array_combine( array1,array2 ) creates an array by combining two other arrays, where the first array is the keys, and the other array is the values. Open Source Programming Array Functions Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow ) Output: <?php $a1=array("a","b","c","d"); $a2=array("Cat","Dog","Horse","Cow"); print_r(array_combine($a1,$a2)); ?> E.g.:
62. 02/21/12 array_count_values( array ) returns an array, where the keys are the original array's values, and the values is the number of occurrences. Open Source Programming <?php $a=array("Cat","Dog","Horse","Dog"); print_r(array_count_values($a)); ?> E.g: Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 ) Output: Array Functions
63. 02/21/12 array_diff( arr1,arr2,… ) function compares two or more arrays, and returns an array with the keys and values from the first array, only if the value is not present in any of the other arrays. Open Source Programming <?php $a1=array(0=>"Cat",1=>"Dog",2=>"Horse"); $a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); print_r(array_diff($a1,$a2)); ?> E.g: Array ( [0] => Cat ) Output: Array Functions
64. 02/21/12 The array_diff_assoc( arr1, arr2,… ) function compares two or more arrays, and returns an array with the keys and values from the first array, only if they are not present in any of the other arrays. Computes the difference of arrays with additional index check. Open Source Programming <?php $a1=array(0=>"Cat",1=>"Dog";,2=>"Horse"); $a2=array(0=>"Rat",1=>"Horse";,2=>"Dog"); $a3=array(0=>"Horse",1=>"Dog",2=>"Cat"); print_r(array_diff_assoc($a1,$a2,$a3)); ?> E.g: Array ( [0] => Cat [2] => Horse ) Output: Array Functions
65. 02/21/12 array_fill ( start,number,value ) function returns an array filled with the values you describe where start is starting index,number defines number of entries. Open Source Programming <?php $a=array_fill(2,3,"Dog"); print_r($a); ?> E.g: Array ( [2] => Dog [3] => Dog [4] => Dog ) Output: Array Functions
66. 02/21/12 The array_flip ( array ) function returns an array with all the original keys as values, and all original values as keys. Open Source Programming <?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse"); print_r(array_flip($a)); ?> E.g: Array ( [Dog] => 0 [Cat] => 1 [Horse] => 2 ) Output: Array Functions
67. 02/21/12 The array_key_exists( key,arr ) function checks an array for a specified key, and returns true if the key exists and false is the key does not exist. Open Source Programming <?php $a=array("a"=>"Dog","b"=>"Cat"); if (array_key_exists("a",$a)) echo "Key exists!"; else echo "Key does not exist!"; ?> E.g: Key exists! Output: Array Functions
68. 02/21/12 The array_merge( array1,array2,array3... ) function merges one or more arrays into one array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Open Source Programming <?php $a1=array("a"=>"Horse","b"=>"Dog"); $a2=array("c"=>"Cow","b"=>"Cat"); print_r(array_merge($a1,$a2)); ?> E.g: Array ( [a] => Horse [b] => Cat [c] => Cow ) Output: Array Functions
72. 02/21/12 The array_pop( array ) function deletes the last element of an array. Array_shift( array ) – removes an element at the beginning of the array Open Source Programming <?php $a=array("Dog","Cat","Horse"); array_pop($a); print_r($a); array_shift($a); print_r($a); ?> E.g: Array ( [0] => Dog [1] => Cat ) Array ( [0] => Cat ) Output: Array Functions
73. 02/21/12 The array_push( array,value1,value2... ) function inserts one or more elements to the end of an array. Array_unshift( array ) – inserts an element at the beginning of the array Open Source Programming <?php $a=array("Dog","Cat"); array_push($a,"Horse","Bird"); Print_r($a); array_unshift($a, “fish”); print_r($a); ?> E.g: Array ( [0] => Dog [1] => Cat [2] => Horse [3] => Bird ) Array ( [0] => fish [1]=>Dog [2] => Cat [3] => Horse [4] => Bird ) Output: Array Functions
74. 02/21/12 array_push — Push one or more elements onto the end of array Open Source Programming <?php $a=array("a"=>"Dog","b"=>"Cat"); array_push($a,"Horse","Bird"); print_r($a); ?> E.g: Array ( [a] => Dog [b] => Cat [0] => Horse [1] => Bird ) Output: Array Functions
75. 02/21/12 array_rand( array,num ) function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key. Open Source Programming <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_rand($a,1)); ?> E.g: b Output: Array Functions
76. 02/21/12 The array_reverse( array,preserve ) function returns an array in the reverse order. Open Source Programming <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_reverse($a)); ?> E.g: Array ( [c] => Horse [b] => Cat [a] => Dog ) Output: Array Functions
77. 02/21/12 The array_search( value,array,strict ) function search an array for a value and returns the key. Open Source Programming <?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); echo array_search("Dog",$a); ?> E.g: a Output: Array Functions
78. 02/21/12 The array_slice( array, start, length, preserve ) function returns selected parts of an array. Open Source Programming <?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2)); ?> E.g: Array ( [0] => Cat [1] => Horse ) Output: Array Functions
79. 02/21/12 The array_splice( array,start,length,array ) function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Open Source Programming <?php $a1=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); $a2=array(0=>"Tiger",1=>"Lion"); array_splice($a1,0,2,$a2); print_r($a1); ?> E.g: Array ( [0] => Tiger [1] => Lion [2] => Horse [3] => Bird ) Output: Array Functions
80. 02/21/12 The array_sum( array ) function returns the sum of all the values in the array. Open Source Programming <?php $a=array(0=>"5",1=>"15",2=>"25"); echo array_sum($a); ?> E.g: 45 Output: Array Functions
81. 02/21/12 The arsort( array,sorttype ) function sorts an array by the values in reverse order. The values keep their original keys. Open Source Programming <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); arsort($my_array); print_r($my_array); ?> E.g: Array ( [c] => Horse [a] => Dog [b] => Cat ) Output: Array Functions
82. 02/21/12 The asort( array,sorttype ) function sorts an array by the values. The values keep their original keys Open Source Programming <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); asort($my_array); print_r($my_array); ?> E.g: Array ( [b] => Cat [a] => Dog [c] => Horse ) Output: Array Functions
83. 02/21/12 The krsort( array,sorttype ) function sorts an array by the keys in reverse order. The values keep their original keys. Open Source Programming <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); krsort($my_array); print_r($my_array); ?> E.g: Array ( [c] => Horse [b] => Cat [a] => Dog ) Output: Array Functions
84. 02/21/12 The ksort( array,sorttype ) function sorts an array by the keys. The values keep their original keys. Open Source Programming <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); ksort($my_array); print_r($my_array); ?> E.g: Array ( [a] => Dog [b] => Cat [c] => Horse ) Output: Array Functions
85. 02/21/12 The rsort( array ) function sorts an array by the values in reverse order. This function assigns new keys for the elements in the array. Existing keys will be removed. Open Source Programming <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); rsort($my_array); print_r($my_array); ?> E.g: Array ( [0] => Horse [1] => Dog [2] => Cat ) Output: Array Functions
86. 02/21/12 The sort( array ) function sorts an array by the values. This function assigns new keys for the elements in the array. Existing keys will be removed. Open Source Programming <?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); sort($my_array); print_r($my_array); ?> E.g: Array ( [0] => Cat [1] => Dog [2] => Horse ) Output: Array Functions
88. 02/21/12 The count_chars( string,mode ) function returns how many times an ASCII character occurs within a string and returns the information. Open Source Programming String Functions Array ( [32] => 1 [33] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 ) Output: <?php $str = "Hello World!"; print_r(count_chars($str,1)); ?> E.g:
89. 02/21/12 The different return modes are: 0 - an array with the ASCII value as key and number of occurrences as value 1 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences greater than zero 2 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences equal to zero are listed 3 - a string with all the different characters used 4 - a string with all the unused characters Open Source Programming String Functions
90. 02/21/12 The explode( separator, string, limit ) function breaks a string into an array. Open Source Programming Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. ) Output: String Functions <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> E.g:
91. 02/21/12 The implode( separator,array ) & join ( separator,array ) function returns a string from the elements of an array. Open Source Programming Hello World! Beautiful Day! Output: String Functions <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?> E.g:
92. 02/21/12 The ltrim( string,charlist ) & rtrim( string,charlist ) function will remove whitespaces or other predefined character from the left and right side of a string respectively. The soundex( string ) function calculates the soundex key of a string. The str_shuffle( string ) function randomly shuffles all the characters of a string. Open Source Programming String Functions
93. 02/21/12 The strlen ( string ) function returns the length of a string. Open Source Programming Length = 12 Output: String Functions <?php $a= “hello World!”; echo “Length = “, strlen($a); ?> E.g:
94. 02/21/12 The strrev ( string ) reverses the given string. Open Source Programming Reverse of “hello World!” is !dlroW olleh Output: String Functions <?php $a= “hello World!”; echo “Reverse of $a is “, strrev($a); ?> E.g:
95. 02/21/12 The strtoupper ( string ) converts to upper case character The strtolower ( string ) converts to lower case character Open Source Programming Upper of “hello World!” is HELLO WORLD! Lower of “hello World!” is hello world Output: String Functions <?php $a= “hello World!”; echo “Upper of $a is “, strtoupper($a); echo “Lower of $a is “, strtolower($a); ?> E.g:
96. 02/21/12 The strpos ( string,exp ) returns the numerical position of first appearance of exp. The strrpos ( string,exp ) returns the numerical position of last appearance of exp. Open Source Programming 2 9 Output: String Functions <?php $a= “hello World!”; echo strpos($a,”l”),”<br>”; echo strrpos($a,”l”); ?> E.g:
97. 02/21/12 The substr ( string,start,length ) function returns a sub string of the size “length” from the position of “start”. Open Source Programming lo Output: String Functions <?php $a= “hello World!”; echo substr($a,3,2); ?> E.g:
98. 02/21/12 The substr_count ( string,substr ) counts number of times a sub string occurred in given string. Open Source Programming 2 Output: String Functions <?php $a= “hello Worlod!”; echo substr_count($a,”lo”); ?> E.g:
99. 02/21/12 The substr_replace ( string,replacement,start,len ) replaces a portion of a string with a replacement string, beginning the substitution at a specified starting position and ending at a predefined replacement length. Open Source Programming heaaorld! Output: String Functions <?php $a= “hello World!”; echo substr_replace($a,”aa”,2,5); ?> E.g:
100. 02/21/12 The ucfirst ( string ) converts the first character to upper case. The ucwords ( string ) converts the first character of each word to upper case. Open Source Programming Hello world! Hello World! Output: String Functions <?php $a= “hello world!”; echo ucfirst($a),”<br>”; echo ucwords($a); ?> E.g:
101. 02/21/12 The parse_str ( string,arr ) function parses a query string into variables. Open Source Programming 23 Kai Jim Output: String Functions <?php parse_str("id=23&name=Kai%20Jim"); echo $id."<br />"; echo $name; ?> E.g:
102. 02/21/12 The str_replace( find,replace,string,count ) function replaces some characters with some other characters in a string. Note: str_ireplace() – for case sensitive Open Source Programming Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1 Output: String Functions <?php $arr = array("blue","red","green","yellow"); print_r(str_ireplace("RED","pink",$arr,$i)); echo "Replacements: $i"; ?> E.g:
103. 02/21/12 The str_pad( string,length,padchar,padtype ) function pads a string to a new length. Open Source Programming .........Hello World Output: String Functions <?php $str = "Hello World"; echo str_pad($str,20,".",STR_PAD_LEFT); ?> E.g:
104. 02/21/12 The str_split( string,length ) function splits a string into an array. Default length is 1. Open Source Programming Array ( [0] => Hel [1] => lo ) Output: String Functions <?php print_r(str_split("Hello",3)); ?> E.g:
105. 02/21/12 The str_word_count( string ) function counts the number of words in a string. Open Source Programming 2 Output: String Functions <?php echo str_word_count("Hello world!"); ?> E.g:
106. 02/21/12 The strcasecmp( string1,string2 ) function compares two strings as case insensitive. Strcmp( string1,string2 ) compares as case sensitive. This function returns: 0 - if the two strings are equal < 0 - if string1 is less than string2 > 0 - if string1 is greater than string2 Open Source Programming 0 1 Output: String Functions <?php echo strcasecmp("Hello world!","HELLO WORLD!"); echo “<br>”; echo strcmp("Hello world!","HELLO WORLD!"); ?> E.g:
107. 02/21/12 The stripos( string,find,start ) function returns the position of the first occurrence of a string inside another string. But doesn’t check for case sensitivity. In strpos it’s d same but check for case sensitivity. Strpos( string,find,start ) – case sensitive. If the string is not found, this function returns FALSE. Open Source Programming 6 Output: String Functions <?php echo stripos("Hello world!","WO"); ?> E.g:
108. 02/21/12 The stristr( string,exp ) function searches for the first occurrence of a string inside another string. This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found Open Source Programming World! Have a nice day Output: String Functions <?php echo stristr("Hello world! Have a nice day","WORLD"); ?> E.g:
109. 02/21/12 Boolean Checkdate( day,month,year ) – used to check the given parameters are a valid date. Date( formatstring ) - The date() function returns a string representation of the current date and/or time formatted according to the instructions specified by a predefined format. Array Getdate ( int timestamp ) – returns array of datetime components Time() – returns time stamp Mktime( int h,int min, int sec, int day, int mnth, int yr ) – create a date and time Open Source Programming Date Functions
110.
111.
112. 02/21/12 $_SERVER: The $_SERVER super global contains information created by the Web server and offers a bevy of information regarding the server and client configuration and the current request environment. $_GET & $_POST: The $_GET and $_POST super globals are used to retrieve information from forms, like user input. $_COOKIE: The $_COOKIE super global stores information passed into the script through HTTP cookies Open Source Programming Super Globals
113. 02/21/12 $_ENV: The $_ENV super global offers information regarding the PHP parser’s underlying server environment. $_SESSION: The $_SESSION super global contains information regarding all session variables $_FILES: The $_FILES super global contains information regarding data uploaded to the server via the POST method. This super global is a tad different from the others. Open Source Programming Super Globals
114.
115. 02/21/12 Function E.g . <?php function generateFooter() { echo "Copyright 2007 W. Jason Gilmore"; } // Once defined, call the function likes so: generateFooter(); // function calling ?> Output: Copyright 2007 W. Jason Gilmore Open Source Programming User Defined Functions
116.
117. 02/21/12 Function with argument: <?php function writeName ($fname ) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName(" Kai Jim "); echo "My sister's name is "; writeName(" Hege "); echo "My brother's name is "; writeName(" Stale "); ?> Open Source Programming Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes. User Defined Functions Formal Argument Fn. Call with Actual Argument
118. 02/21/12 Function with arguments & return value: <?php function calculateAmt ($cost, $num ) { return ($cost * $num); } $price=10; $tot=5; Echo “ Total Amount “, calculateAmt($price, $tot); ?> Open Source Programming Output: Total Amount 50 User Defined Functions
119. 02/21/12 Fn. Call by Ref.: <?php $cost = 20.99; $tax = 0.0575; function calculateCost( & $cost, $tax) { // Modify the $cost variable $cost = $cost + ($cost * $tax); // Perform some random change to the $tax variable. $tax += 4; } Echo “(bfr fn call) Cost is $cost <br>”; calculateCost($cost, $tax); Echo "Tax is $tax*100 <br>"; Echo “(aft fn call) Cost is: $cost”; ?> Open Source Programming Output: (bfr fn call) Cost is 20.99 Tax is 5.75 (aft fn call) Cost is: 22.20 User Defined Functions
120.
121.
122. 02/21/12 Open Source Programming PHP Form Handling < form method = POST action = form.php> Name: < input type =text name = fname > <br > Age: < input type = text name = age > < br > < input type = submit value = submit> </ form > HTML Code (Form.html) <?php $a = $_POST[' fname ']; $b = $_POST[' age ']; echo "Welcome Mr./Ms. $a. You are $b years old "; ?> PHP Code (form.php)
124. 02/21/12 Open Source Programming Open Source Programming 1. The application attempts something. 2. If the attempt fails, the exception-handling feature throws an exception. 3. The assigned handler catches the exception and performs any necessary tasks. 4 . The exception-handling feature cleans up any resources consumed during the attempt. In PHP, Exception handling can be done by try …throw… catch . Exception Handling PHP
125. 02/21/12 Open Source Programming Open Source Programming Exception handling syntax: Try { statement block; if goes wrong throw new exception(error message) } catch (exception $E) { echo $E.getMessage(); } Exception Handling PHP
126. 02/21/12 <?php $a=10; $b=0; try { if ($b == 0) throw new exception("Divide by zero error"); $c = $a/$b; echo " $a"," / ","$b = ", $a/$b; } catch(Exception $e) { echo $e->getMessage(); } ?> Open Source Programming Output: Divide by zero error Exception Handling in PHP
127.
128.
129.
130. 02/21/12 <?php class ExtendClass extends SimpleClass { // Redefine the parent method function displayVar() { echo "Extending class"; parent::displayVar(); } } $extended = new ExtendClass(); $extended->displayVar(); ?> Open Source Programming Extending class Hello E.G . Output: Inheritance
131.
132. 02/21/12 E.g . <?php class BaseClass { function __construct() { print "In BaseClass constructor"; } } class SubClass extends BaseClass { function __construct() { parent::__construct(); print "In SubClass constructor"; } } $obj = new BaseClass(); $obj = new SubClass(); ?> Output: In BaseClass constructor In BaseClass constructor In SubClass constructor Open Source Programming Constructors & Destructors
133.
134. 02/21/12 E.g. <?php class foo { public function printItem($string) { echo 'Foo: ' . $string . PHP_EOL; } public function printPHP() { echo 'PHP is great.' . PHP_EOL; } } class c extends foo { public function printItem($string) { echo "Extending from FOO"; parent::printItem("this is gud"); } } $foo = new foo(); $c = new c(); $foo->printItem('baz'); ' $foo->printPHP(); $c->printItem('from C'); $c->printPHP(); ?> Foo: baz PHP is great. Extending from FOO Foo: this is gud PHP is great. Output: Open Source Programming Overloading
135. 02/21/12 Open Source Programming Can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function. The include() function takes all the content in a specified file and includes it in the current file. Files are included based on the file path given . The two functions are identical in every way, except how they handle errors: 1. include() generates a warning, but the script will continue execution 2. require() generates a fatal error, and the script will stop E.g. <?php include("wrongFile.php"); echo "Hello World!"; ?> Output: Error Message Hello World Include & Require
136. 02/21/12 Open Source Programming E.g. <?php require("wrongFile.php"); echo "Hello World!"; ?> Output: Error Message Include & Require
137.
138.
139. 02/21/12 File closing can be done by fclose(fp); E.g. <?php $ourFileName = "testFile.txt"; $ourFileHandle = fopen($ourFileName, ‘w') or die("can't open file"); fclose($ourFileHandle); ?> Files
140. 02/21/12 Open Source Programming 1) fopen(filename,mode) - used for opening a file with specific mode. 2) fclose(fp) - used to close the file. (fp -> filepointer) 3) feof(fp) - used to find the End of File 4) fgetc(fp) - Gets character from file pointer 5) fgets(fp) - Gets a line from file pointer 6) fread(fp,size) - Binary-safe file read 7) fscanf(fp,format) - Parses input from a file according to a format 8) fwrite(fp,string) - Binary-safe file write 9) file_put_contents(fp,string) - Write a string to a file 10) file_get_contents(fp) - Reads entire file into a string 11) file(fp) - Reads entire file into an array 12) file_exists(fp) - Checks whether a file or directory exists Some File Functions
141. 02/21/12 Open Source Programming 13) is_readable(fp) - Tells whether the filename is readable 14) is_writable(fp) - Tells whether the filename is writable 15) is_file(path) - Tells whether the filename is a regular file 16) is_dir(path) - Tells whether the filename is a directory 17) is_link(path) - Tells whether the filename is a symbolic link 18) readlink(path) - Returns the target of a symbolic link 19) readdir - Read entry from directory handle 20) glob - Find pathnames matching a pattern 21) filesize(fp) - Gets file size 22) filetype(fp) - Gets file type 23) fprintf(fp,format) - Write a formatted string to a stream 24) fstat(fp) - Gets information about a file using an open file pointer Some File Functions
142. 02/21/12 Open Source Programming <?php $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Bobby Bopper"; fwrite($fh, $stringData); $stringData = "Tracy Tanner"; fwrite($fh,$stringData); fclose($fh); ?> E.g. <?php $ourFileName = "testFile.txt"; $ourFileHandle = fopen($ourFileName, ‘w') or die("can't open file"); ?> File Write
143. 02/21/12 Open Source Programming E.g. <?php // get contents of a file into a string $filename = "testfile.txt"; $handle = fopen($filename, "r"); //$contents = fread($handle, filesize($filename)); while (!feof($handle)) echo fgetc($handle),"<br>"; //print_r("$contents"); fclose($handle); ?> Output: Bobby Bopper Tracy Tanner File Read
144. 02/21/12 Open Source Programming E.g. <?php $myFile = "testFile.txt"; $fh = fopen($myFile, 'a+') or die("can't open file"); $stringData = "new1"; fwrite($fh, $stringData); $stringData = "new2"; fwrite($fh, $stringData); fclose($fh); ?> Output: Bobby Bopper Tracy Tannernew1new2 File Append