Transcript
04/10/23 1
Open Source Programming
04/10/23 2Open 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.
04/10/23 3
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.
What is Open source
Open Source Programming
04/10/23 4
Why OSP ROCKS?
They are cross-platform and “technology-
neutral.”They embrace diversity.
They are free.
Open Source Programming
04/10/23 5
OSP Software - OS Linux — operating system kernel based on Unix GNU OS — a complete Unix-like operating system OpenBSD — produces a FREE, UNIX-like operating system.(Berkeley Systems Distribution) FreeBSD — operating system derived from Unix an advanced operating system for modern server, desktop, and embedded computer platforms OpenSolaris — Unix Operating System from Sun Microsystems Symbian — real-time mobile operating system designed for smartphones.
Open Source Programming
04/10/23 6
OSP Software - Server
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
04/10/23 7
WordPress — blog software MongoDB — document-oriented, non-relational
database Moodle — course management system or virtual learning environment openSIS — open source Student Information System
OSP Software
Open Source Programming
04/10/23 8
osCommerce — allows store owners to setup, run, and maintain online stores with minimum effort and with no costs
PeaZip — 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
04/10/23 9
OSP Software (Others)
PHP — Hypertext Preprocessor Ruby,Tcl/Tk
PERL & Python — Interpreted Dynamic Language
MySQL — Data Base
Open Source Programming
open source companies• IBM
• uses and develops Apache and Linux;
• Apple• released core layers of Mac OS X Server
as an open source BSD operating system called Darwin; open sourcing the QuickTime Streaming Server and the OpenPlay network gaming toolkit
• HP• uses and releases products running
Linux
04/10/23 10
04/10/23 11
•Sunsupports some open source development
•Red Hat SoftwareLinux vendor
04/10/23 12
04/10/23 13
Intro to AMP Package
MySQL: It enables PHP and Apache to work together to access and display data in a readable format to a browser.
Open Source Programming
AMP is an acronym formed from the initials of Apache, MySQL and PHP or Python or Perl.
Apache: It acts as Web server. Its main job is to parse any file requested by a browser and display the correct results according to the code within that file. PHP: PHP is a server-side scripting language that allows your Web site to be truly dynamic.
04/10/23 14Open Source Programming
AMP as Restaurant
Apache – This is the Chef. Whatever people ask for, prepares it without complaint. She is quick, flexible, and able to prepare a multitude of different types of foods.
04/10/23 15
AMP as Restaurant
PHP – This is the Waiter, gets requests from the patron and carries them back to the kitchen with specific instructions about how the meal should be prepared.
Open Source Programming
04/10/23 16
AMP as Restaurant
MySQL – This is Stockroom of ingredients.
Open Source Programming
LICENSES • License that are popular and
widely used or with strong communities ::.
• Apache License, 2.0 (Apache-2.0)• BSD 3-Clause "New" or "Revised"
license (BSD-3-Clause)• BSD 3-Clause "Simplified"
or"FreeBSD" license (BSD-2-Clause)
04/10/23 17
04/10/23 18
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)
04/10/23 19
•Appache is a open source Web server Responds to client requests by providing resources•Web server and client communicate with platform-independent Hypertext Transfer Protocol (HTTP).•Apache server runs mostly on unix,linux and solaris platform.•It is secure (password protected pages)•It has been tested thoroughly by developers and usersCorrectness(It MUST conform to the HTTP spec)Speed
Apache Introduction
Open Source Programming
04/10/23 20
• Request methods– get– post– Retrieve and send client form data to
Web server– Post data to a server-side form
handler
Open Source Programming
HTTP request types
04/10/23 21
• Multi-tier application (n-tier application)
– Information tier (data or bottom tier)• Maintains data for the application• Stores data in a relational database management
system (RDBMS)– Middle tier
• Implements business logic and presentation logic• Control interactions between application clients
and application data– Client tier (top tier)
• Application’s user interface• Users interact directly with the application
through the client tier
Open Source Programming
System Architecture
04/10/23 22Open Source Programming
Overview of Php• PHP Hypertext Preprocessor.
– Other Names : Personal Home Page, Professional Home Page
• PHP is a server side scripting language.– Capable of generating the HTML pages
• HTML generates the web page with the static text and images.
• However the need evolved for dynamic web based application, mostly involving database usage.
• create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools.
04/10/23 23
Features of PHP
• Is an open source.
• There are no. of server side scripting available likeASP, SSJS, JSP…..
• PHP involves simplicity in scripting (..generally using the database) platform independence.• PHP is primarily designed for web applications
well optimized for the response times needed for web applications
Open Source Programming
04/10/23 24Open Source Programming
CLIENT
WEB SERVER
HTTP Request(url)
<HTML><?php PHP code ?></HTML>
Gets Page
<HTML><B>Hello</B></HTML>
Interprets the PHP codeServer response
How it works?
Browser creates the web page
04/10/23 25
PHP with HTML
Open Source Programming
PHP programs are written using a text editor, such as Notepad or WordPad, just like HTML pages.
PHP pages, for the most part, end in a .php extension. This extension signifies to the server that it needs to parse the PHP code before sending the resulting HTML code to the viewer’s Web browser.
04/10/23 26Open Source Programming
PHP with HTML
What makes PHP so different is that it not only allows HTML pages to be created.
It is invisible to your Web site visitors. The only thing they see the resulting HTML output. This gives you more security for your PHP code and more flexibility in writing it.
HTML can also be written inside the PHP section of your page.
PHP can also be written as a standalone program, with no HTML
04/10/23 27Open Source Programming
PHP Syntax
PHP is denoted in the page with opening and closing tags as follows:
<?php //php code;?>
04/10/23 28
<HTML><HEAD><TITLE>My First PHP Program</TITLE> <h1></HEAD><BODY><?phpecho “I’m a PHP Program.”;?></BODY></HTML>
Open Source Programming
PHP Programs
CodeResult
04/10/23 29
<?php$name=“VIT UNIVERSITY”;echo ‘My name is ‘,$name;?>
Open Source Programming
PHP Programs
Code Result
04/10/23 30
Data Type
• PHP is an untyped language – variables type can change on the fly.
• Four basic data types:
• More data types
1. Integer2. Double3. String4. Boolean
1. Array2. Object
Open Source Programming
04/10/23 31
• ..values that never changes.
• Constants are defined in PHP by using the define( ) function.– For e.g.
define(“NCST”, “National Centre for Software Technology”)
• defined() function says whether the constant exists or not.
Constants
Open Source Programming
04/10/23 32
Variables
• The variables in PHP are declared by appending the $ sign to the variable name.– For e.g
$company = “NCST”;$sum = 10.0;
• Variable’s data type is changed by the value that is assigned to the variable.
• Type casting allows to change the data type explicitly.
Open Source Programming
04/10/23 33
Variables
Open Source Programming
Rules for Naming Variables:
In PHP, unlike some other programming languages, there is no restriction on the size of a variable name.
Variable names should identified by dollar ($)
symbol.
Variable names can begin with an underscore.
Variable names cannot begin with a numeric character.
Variable names must be relevant and self-explanatory.
04/10/23 34
Variables
Open Source Programming
Valid Examples Non Valid Examples
$prod_desc $9OctSales$Intvar Sales123$_Salesamt $*asgs
04/10/23 35
$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";
Variables (cont)
Open Source Programming
04/10/23 36
Settype
Open Source Programming
In PHP, Variable type can be changed by Settype
Syntax:Settype(Variablename, “newDataType”);
E.g.$pi = 3.14 //floatSettype($pi,”string”); //now string – “3.14”Settype($pi,”integer”);// now integer - 3
Settype
04/10/23 37
Settype & Gettype
Open Source Programming
Syntax:Gettype(Variablename);
E.g.$pi = 3.14; //floatprint 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.
04/10/23 38
Operators
• All the operators such as arithmetic, assignment, Comparison, and logical operators are similar to the operators in C and C++.
• In PHP the string concatenation
operator is denoted by ‘.’– For e.g.
$name = “My name is”.$myname;
Open Source Programming
04/10/23 39
Quotes (“ Vs. ‘)
Open Source Programming
In a double-quoted string any variable names are expanded to their values.
In a single-quoted string, no variable expansion takes place.
$name = "Phil";$age = 23;echo '$name is $age';
$name = "Phil";$age = 23;echo “$name is $age”;
Output is $name is $age
Output is Phil is 23
04/10/23 40
Operators (cont)
Comparison Operator
Logical Operator
And
Or
!
Xor
&& ( high precedence)
|| ( high precedence)
==
!=
<
>
<=
>=
===(identical)
Open Source Programming
04/10/23 41
Comment Line in PHP
Open Source Programming
1.Single Line Comment - Single line comment in PHP is identified with //.
<?Php // my first prg ?>
2.Multi Lines Comment - Multi lines comment in PHP is identified by /* … */
<?Php /* line1
line2line 3 */
?>
04/10/23 42
Output in PHP
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
?>
04/10/23 43
Output in PHP
Open Source Programming
3. Output the value of a PHP variable:
<?php echo $hits; // prints out the number of hitsprint ($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 ?>
04/10/23 44
Conditional Statements(Branching)
1. If…else Statement – single decision stmt
if (<condition>) {
//True part Php code }
else {
//False part php code }
if ($num1 > $num2) {
$max = $num1; }
else { $max = $num2;
}
Syntax E.g.
Open Source Programming
04/10/23 45
2. If…else if Statement – multiple decision stmt
if (<condition1>) {
//True part Php code }
else if (<condition2>) {
//1st False 2nd true part php code } else { // false part PhP code }
if ($num1 > $num2) {
$max = $num1; }
else if ($num2 > $num3) { $max = $num3;
} else $max = $num2;
Syntax
E.g.
Conditional Statements (Branching)
Open Source Programming
04/10/23 46
3. Switch Statement – replacement of “if …… else if stmt”.
switch (expression){ case value1: {stmts1; break;} case value2: {stmts2; break;} ………… ………… [default: stmts;]}
switch ($day){ case 1: {echo “its Sunday”; break;} case 2: {echo “its Monday”; break;} ……… ……… case 7: {echo “its Saturday”; break;} default: {echo “not specified value”;}}
SyntaxE.g.
Conditional Statements (Branching)
Open Source Programming
04/10/23 47Open Source Programming
4. For Statement – replacement of “if …… else if stmt”.
for( initial_expression; termination_check; index_updation){ statement (S);}
for($i=1; $i < 10; $i++)echo $i;
(or)$i=1;for(;$i<10;) { echo $i; $i=$i+1; }
Syntax E.g.
Conditional Statements (Looping)
04/10/23 48
5. Do … While Statement
do{ Statement (S);} while (<condition>);
do{ $i=$i+1; echo $i;} while ($i < 10);
Syntax E.g.
Conditional Statements (Looping)
Open Source Programming
04/10/23 49
5. While Statement
while(<condition>){ Statement (S);}
while ($i < 10){
$i=$i+1; echo $i;}
Syntax E.g.
Conditional Statements (Looping)
Open Source Programming
04/10/23 50
Arrays
In Php, arrays are lists of bits of information mapped with keys and stored under one variable name. For example, you can store a person’s name and address or a list of states in one variable.
Open Source Programming
Generally, array is a collection of homogeneous elements.
Let’s store a person’s name and age under one variable name :
$name = array(‘firstname’=>’Albert’,‘lastname’=>’Einstein’,‘age’=>124);
04/10/23 51Open Source Programming
<?php$name[’firstname’] = “Albert”;$name[’lastname’] = “Einstein”;$name[’age’] = 124;?>
<?php$flavor[] = ‘blue rasberry’;$flavor[] = ‘root beer’;$flavor[] = ‘pineapple’;?>
Array with
Implicit key
Array with
Explicit key
Arrays
04/10/23 52
Multidimensional Arrays
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
04/10/23 53
$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/>";}}?>
04/10/23 54
Output :0 is ArrayThe actual user is 0.---> name -> James ---> sex -> Male ---> age -> 28 1 is ArrayThe actual user is 1.---> name -> John ---> sex -> Male ---> age -> 25 2 is ArrayThe actual user is 2.---> name -> Susan ---> sex -> Female ---> age -> 24
04/10/23 55
<html><body><FORM ACTION =“arr.php" METHOD = "post">ur name<INPUT TYPE="text" NAME="ur name"><br>cost<INPUT TYPE="text" NAME="cost"><br>days<INPUT TYPE="text" NAME="days"><br><INPUT TYPE="submit"name="submit"><br><?phpif(isset($_POST['submit'])){$d[0]=$_POST['cost'];$d[1]=$_POST['days'];$d[2]=$d[0]+$d[1];echo "output <INPUT TYPE=text value=$d[2]>";foreach($d as $v)echo "output <INPUT TYPE=text value=$v>"}?></body></form></html>
04/10/23 56
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.
Functions
Open Source Programming
04/10/23 57Open Source Programming
Array Functions
<?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.:
04/10/23 58Open Source Programming
Array Functions
array_chunk(array,size,preserve_key ) - splits an array into chunks of new arrays
04/10/23 59
Array ([0] => Array ( [0] => Cat [1] => Dog )[1] => Array ( [0] => Horse [1] => Cow ))
Output:
<?php$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");print_r(array_chunk($a,2));?>
E.g.: 1
Open Source Programming
Array Functions
04/10/23 60
Array ([0] => Array ( [a] => Cat [b] => Dog )[1] => Array ( [c] => Horse [d] => Cow ))
Output:
<?php$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");print_r(array_chunk($a,2,true));?>
E.g.: 2
Open Source Programming
Array Functions
04/10/23 61
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.:
04/10/23 62
array_count_values(array) returns an array, where the keys are the original array's values, and the values is the number of occurrences.
<?php$a=array("Cat","Dog","Horse","Dog");print_r(array_count_values($a));?>
E.g:
Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 )
Output:
Open Source Programming
Array Functions
04/10/23 63
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.
<?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:
Open Source Programming
Array Functions
04/10/23 64
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.
<?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:
Open Source Programming
Array Functions
04/10/23 65
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.
<?php$a=array_fill(2,3,"Dog");print_r($a); ?>
E.g:
Array ( [2] => Dog [3] => Dog [4] => Dog )
Output:
Open Source Programming
Array Functions
04/10/23 66
The array_flip(array ) function returns an array with all the original keys as values, and all original values as keys.
<?php$a=array(0=>"Dog",1=>"Cat",2=>"Horse");print_r(array_flip($a));?>
E.g:
Array ( [Dog] => 0 [Cat] => 1 [Horse] => 2 )
Output:
Open Source Programming
Array Functions
04/10/23 67
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.
<?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:
Open Source Programming
Array Functions
04/10/23 68
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. <?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:
Open Source Programming
Array Functions
04/10/23 69
<?php$a=array(0=>"v",1=>"h");$a1=array(1=>"h",2=>"g");print_r(array_merge($a,$a1))f;?>
E.g:
Array ( [0] => Horse [1] => Dog )
Output:
Open Source Programming
Array Functions
04/10/23 70
array_multisort(array1, sortingorder,
sorting type, array2, array3 ) returns a sorted array. You can assign one or more arrays.
<?php$a1=array(“Dog","Cat");$a2=array("Fido","Missy");array_multisort($a1,$a2);print_r($a1);print_r($a2);?>
E.g:
Array ( [0] => Cat [1] => Dog )Array ( [0] => Missy [1] => Fido )
Output:
Open Source Programming
Array Functions
04/10/23 71
<?php $a1=array("Dog","Dog","Cat"); $a2=array("Pluto","Fido","Missy"); array_multisort($a1,SORT_ASC,$a2,SORT_DESC); print_r($a1); print_r($a2); ?>
E.g:
Array ( [0] => Cat [1] => Dog [2] => Dog ) Array ( [0] => Missy [1] => Pluto [2] => Fido )
Output:
Open Source Programming
Array Functions
04/10/23 72
The array_pop(array) function deletes the last
element of an array. Array_shift(array) – removes an element at the beginning of the array
<?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:
Open Source Programming
Array Functions
04/10/23 73
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
<?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:
Open Source Programming
Array Functions
04/10/23 74
<?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_push — Push one or more elements onto the end of array
Open Source Programming
Array Functions
04/10/23 75
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.
<?php$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");print_r(array_rand($a,1));?>
E.g:
b
Output:
Open Source Programming
Array Functions
04/10/23 76
The array_reverse(array,preserve) function returns an array in the reverse order.
<?php$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");print_r(array_reverse($a));?>
E.g:
Array ( [c] => Horse [b] => Cat [a] => Dog )
Output:
Open Source Programming
Array Functions
04/10/23 77
The array_search(value,array,strict ) function search an array for a value and returns the key.
<?php$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");echo array_search("Dog",$a);?>
E.g:
a
Output:
Open Source Programming
Array Functions
04/10/23 78
The array_slice(array, start, length, preserve) function returns selected parts of an array.
<?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:
Open Source Programming
Array Functions
04/10/23 79
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.
<?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:
Open Source Programming
Array Functions
04/10/23 80
The array_sum(array) function returns the sum of all the values in the array.
<?php$a=array(0=>"5",1=>"15",2=>"25");echo array_sum($a); ?>
E.g:
45
Output:
Open Source Programming
Array Functions
04/10/23 81
The arsort(array,sorttype) function sorts an array by the values in reverse order. The values keep their original keys.
<?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:
Open Source Programming
Array Functions
04/10/23 82
The asort(array,sorttype) function sorts an array by the values. The values keep their original keys
<?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:
Open Source Programming
Array Functions
04/10/23 83
The krsort(array,sorttype) function sorts an array by the keys in reverse order. The values keep their original keys.
<?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:
Open Source Programming
Array Functions
04/10/23 84
The ksort(array,sorttype) function sorts an array by the keys. The values keep their original keys.
<?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:
Open Source Programming
Array Functions
04/10/23 85
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.
<?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:
Open Source Programming
Array Functions
04/10/23 86
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.
<?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:
Open Source Programming
Array Functions
04/10/23 87
CASE_LOWER
CASE_UPPER
SORT_ASC
SORT_DESC
SORT_REGULAR
SORT_NUMERIC
SORT_STRING
SORT_LOCALE_STRING
COUNT_NORMAL
COUNT_RECURSIVE
Open Source Programming
Array Constants
EXTR_OVERWRITE
EXTR_SKIP
EXTR_PREFIX_SAME
EXTR_PREFIX_ALL
EXTR_PREFIX_INVALID
EXTR_PREFIX_IF_EXISTS
EXTR_IF_EXISTS
EXTR_REFS
04/10/23 88
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:
04/10/23 89
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
04/10/23 90
The explode(separator, string, limit) function breaks a string into an array.
Open Source Programming
String Functions
<?php$str = "Hello world. It's a beautiful day.";print_r (explode(" ",$str));?>
E.g:
Array([0] => Hello[1] => world.[2] => It's[3] => a[4] => beautiful[5] => day.)
Output:
04/10/23 91
The implode(separator,array ) &
join(separator,array ) function returns a string from the elements of an array.
Open Source Programming
String Functions
<?php$arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr);?>
E.g:
Hello World! Beautiful Day!
Output:
04/10/23 92
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
04/10/23 93
The strlen(string) function returns the length of a string.
Open Source Programming
String Functions
<?php$a= “hello World!”;echo “Length = “, strlen($a);?>
E.g:
Length = 12
Output:
04/10/23 94
The strrev(string) reverses the given string.
Open Source Programming
String Functions
<?php$a= “hello World!”;echo “Reverse of \”$a\” is “, strrev($a);?>
E.g:
Reverse of “hello World!” is !dlroW olleh
Output:
04/10/23 95
The strtoupper(string) converts to upper case character
The strtolower(string) converts to lower case character
Open Source Programming
String Functions
<?php$a= “hello World!”;echo “Upper of \”$a\” is “, strtoupper($a);echo “Lower of \”$a\” is “, strtolower($a);?>
E.g:
Upper of “hello World!” is HELLO WORLD!Lower of “hello World!” is hello world
Output:
04/10/23 96
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
String Functions
<?php$a= “hello World!”;echo strpos($a,”l”),”<br>”;echo strrpos($a,”l”);?>
E.g:
29
Output:
04/10/23 97
The substr(string,start,length) function returns a sub string of the size “length” from the position of “start”.
Open Source Programming
String Functions
<?php$a= “hello World!”;echo substr($a,3,2);?>
E.g:
lo
Output:
04/10/23 98
The substr_count(string,substr) counts number of times a sub string occurred in given string.
Open Source Programming
String Functions
<?php$a= “hello Worlod!”;echo substr_count($a,”lo”);?>
E.g:
2
Output:
04/10/23 100
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
String Functions
<?php$a= “hello world!”;echo ucfirst($a),”<br>”;echo ucwords($a); ?>
E.g:
Hello world!Hello World!
Output:
04/10/23 101
The parse_str(string,arr) function parses a query string into variables.
Open Source Programming
String Functions
<?phpparse_str("id=23&name=Kai%20Jim");echo $id."<br />";echo $name;?>
E.g:
23Kai Jim
Output:
04/10/23 102
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
String Functions
<?php$arr = array("blue","red","green","yellow");print_r(str_ireplace("RED","pink",$arr,$i));echo "Replacements: $i";?>
E.g:
Array([0] => blue[1] => pink[2] => green[3] => yellow)Replacements: 1
Output:
04/10/23 103
The str_pad(string,length,padchar,padtype) function pads a string to a new length.
Open Source Programming
String Functions
<?php$str = "Hello World";echo str_pad($str,20,".",STR_PAD_LEFT);?>
E.g:
.........Hello World
Output:
04/10/23 104
The str_split(string,length ) function splits a string into an array. Default length is 1.
Open Source Programming
String Functions
<?phpprint_r(str_split("Hello",3));?>
E.g:
Array([0] => Hel[1] => lo)
Output:
04/10/23 105
The str_word_count(string) function counts the number of words in a string.
Open Source Programming
String Functions
<?phpecho str_word_count("Hello world!");?>
E.g:
2
Output:
04/10/23 106
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
String Functions
<?phpecho strcasecmp("Hello world!","HELLO WORLD!");echo “<br>”;echo strcmp("Hello world!","HELLO WORLD!");?>
E.g:
01
Output:
04/10/23 107
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
String Functions
<?phpecho stripos("Hello world!","WO");?>
E.g:
6
Output:
04/10/23 108
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
String Functions
<?phpecho stristr("Hello world! Have a nice day","WORLD");?>
E.g:
World! Have a nice day
Output:
04/10/23 109
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
04/10/23 110
Some mathematical functions are listed:
1. sin(X) , cos(x), tan(x), asin(x), acos(x), atan(x), exp(x), log(x) – are trigonometric functions returns the respected values.
2. Ceil(x), floor(x) – used to round the numbers.
3. Abs(x) – returns absolute value for the given number.
4. Fmod(x,y) – returns the reminder of the division x /y.
5. Min(x,y) & Max(x,y) – returns the min and max values respectively.
6. Bindec(x), binoct(x),binhex(x) – converts the given binary value into decimal, octal and hexadecimal.
7. decbin(x), decoct(x), dechex(x) – converts the given decimal value into binary, octal and hexadecimal.
8. Base_convert(val,bastype, convtype) – converts the given value of basetype has to be converted to the convtype.
Open Source Programming
Math Functions
04/10/23 111
PHP offers a number of useful predefined variables that are accessible from anywhere within the executing script and provide you with a substantial amount of environment-specific information. You can sift through these variables to retrieve details about the current user session, the user’s operating environment, the local operating environment, and more.
They are:
$_SERVER$_GET $_POST$_COOKIE $_ENV$_SESSION$_FILES
Open Source Programming
Super Globals
04/10/23 112
$_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
04/10/23 113
$_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
04/10/23 114
Creating Function:
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
A piece of information passed to a function is called an argument.
Some functions require that more than one argument be passed to them. Arguments in these cases must be separated by commas:
Open Source Programming
User Defined Functions
04/10/23 115
Function E.g.
<?phpfunction 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
04/10/23 116
Function Call:
A function call consists of the functionName(parameters) followed by parentheses.
A function can return a value using the return statement in conjunction with a value or object.
The function can be called as pass-by-value and pass-by-reference. By default, parameters are passed to functions by value.
Open Source Programming
User Defined Functions
04/10/23 117
Function with argument:
<?phpfunction 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
User Defined Functions
Output:
My name is Kai Jim Refsnes.My sister's name is Hege Refsnes.My brother's name is Stale Refsnes.
Formal Argument
Fn. Call with Actual Argument
04/10/23 118
Function with arguments & return value:
<?phpfunction calculateAmt($cost, $num){return ($cost * $num); }$price=10;$tot=5;Echo “ Total Amount “, calculateAmt($price, $tot);?>
Open Source Programming
User Defined Functions
Output:
Total Amount 50
04/10/23 119
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
User Defined Functions
Output:
(bfr fn call) Cost is 20.99Tax is 5.75(aft fn call) Cost is: 22.20
04/10/23 120
Variable Scope:
Variables used inside a function are different from those used outside a function. The variables used inside the function are limited to the scope of the function.
The global statement declares a variable within a function as being the same as the variable that is used outside of the function.
Open Source Programming
User Defined Functions
04/10/23 121
Fn. With global variable:
<?phpfunction doublevalue( ){global $temp;$temp = $temp * 2;}$temp = 5;doublevalue( );echo “Temp is: $temp";
?>
Open Source Programming
User Defined Functions
Output:
Temp is: 10
04/10/23 122Open 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)
04/10/23 123Open Source Programming
HTML Browser Result
PHP Form Handling
04/10/23 124Open Source ProgrammingOpen Source Programming
Exception Handling PHP
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.
04/10/23 125Open Source ProgrammingOpen Source Programming
Exception Handling PHP
Exception handling syntax:
Try
{
statement block;
if goes wrong throw new exception(error message)
} catch (exception $E)
{
echo $E.getMessage();
}
04/10/23 126
<?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
Exception Handling in PHP
Output:Divide by zero error
04/10/23 127Open Source Programming
Object Oriented PHP - Class
Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.
The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
$this is a variable that indicates the current object. For instance, $this->a gets the data from the $a variable in the object.
04/10/23 128Open Source Programming
E.g.:
<?phpclass SimpleClass{ // property declaration public $var = ‘Hello';
// method declaration public function displayVar() { echo $this->var; }$obj1 = new SimpleClass();$Obj1->displayVar();}?>
To create an instance of a class, the new keyword must be used.
Now any abc object that is created contains a property called $var with the value of “Hello”. This property can be accessed and even be changed with the help of objects.
In this, the -> operator is used to access the properties or methods of the object.
Object Oriented PHP - Object
04/10/23 129Open Source Programming
Inheritance
A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.
The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class.
However, if the parent class has defined a method as final, that method may not be overridden.
It is possible to access the overridden methods or static properties by referencing them with parent.
Abstract methods are special in that they are declared only within a parent class but are implemented in child classes. Only classes declared as abstract can contain abstract methods.
04/10/23 130
<?phpclass ExtendClass extends SimpleClass{ // Redefine the parent method function displayVar() { echo "Extending class\n"; parent::displayVar(); }}
$extended = new ExtendClass();$extended->displayVar();?>
Open Source Programming
Inheritance
Extending class Hello
E.G.
Output:
04/10/23 131Open Source Programming
Constructors & Destructors
A constructor is defined as a block of code that automatically executes at the time of object instantiation.
PHP recognizes constructors by the name __construct().
PHP does not automatically call the parent constructor; you must call it explicitly using the parent keyword.
Destructors are created like any other method but must be titled __destruct().
04/10/23 132
E.g.
<?phpclass BaseClass { function __construct() { print "In BaseClass constructor\n"; }}
class SubClass extends BaseClass { function __construct() { parent::__construct(); print "In SubClass constructor\n"; }}
$obj = new BaseClass();$obj = new SubClass();?>
Output:
In BaseClass constructor In BaseClass constructor In SubClass constructor
Open Source Programming
Constructors & Destructors
04/10/23 135Open Source Programming
Include & Require
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.
<?phpinclude("wrongFile.php");echo "Hello World!";?>
Output:
Error MessageHello World
04/10/23 136Open Source Programming
Include & Require
E.g.
<?phprequire("wrongFile.php");echo "Hello World!";?>
Output:
Error Message
04/10/23 137Open Source Programming
Files Organizing related data into entities commonly referred to as files.
To create a file we use fopen Function. The fopen function needs two important pieces of information to operate correctly.
First parameter requires file name to open.
Second parameter indicates the mode in which the file has to be opened.E.g.
<?php$ourFileName = "testFile.txt";$ourFileHandle = fopen($ourFileName, ‘w‘)?>
04/10/23 138Open Source Programming
Files
Some modes are
04/10/23 139
Files
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);?>
04/10/23 140Open Source Programming
Some File Functions1) 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 File4) fgetc(fp) - Gets character from file pointer5) fgets(fp) - Gets a line from file pointer6) fread(fp,size) - Binary-safe file read7) fscanf(fp,format) - Parses input from a file according to a format8) fwrite(fp,string) - Binary-safe file write9) file_put_contents(fp,string) - Write a string to a file10) file_get_contents(fp) - Reads entire file into a string11) file(fp) - Reads entire file into an array12) file_exists(fp) - Checks whether a file or directory exists
04/10/23 141Open Source Programming
Some File Functions
13) is_readable(fp) - Tells whether the filename is readable14) is_writable(fp) - Tells whether the filename is writable15) is_file(path) - Tells whether the filename is a regular file16) is_dir(path) - Tells whether the filename is a directory17) is_link(path) - Tells whether the filename is a symbolic link18) readlink(path) - Returns the target of a symbolic link19) readdir - Read entry from directory handle20) glob - Find pathnames matching a pattern21) filesize(fp) - Gets file size22) filetype(fp) - Gets file type23) fprintf(fp,format) - Write a formatted string to a stream24) fstat(fp) - Gets information about a file using an open file pointer
04/10/23 142Open Source Programming
File Write
<?php $myFile = "testFile.txt";$fh = fopen($myFile, 'w') or die("can't open file");$stringData = "Bobby Bopper\n";fwrite($fh, $stringData);$stringData = "Tracy Tanner\n";fwrite($fh,$stringData);fclose($fh); ?>
E.g.
<?php$ourFileName = "testFile.txt";$ourFileHandle = fopen($ourFileName, ‘w') or die("can't open file");?>
04/10/23 143Open Source Programming
File Read
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
04/10/23 144Open Source Programming
File Append
E.g. <?php $myFile = "testFile.txt";$fh = fopen($myFile, 'a+') or die("can't open file");$stringData = "new1";fwrite($fh, $stringData);$stringData = "new2\n";fwrite($fh, $stringData);fclose($fh); ?>
Output:
Bobby Bopper Tracy Tannernew1new2
04/10/23 145
04/10/23 146
top related