SlideShare a Scribd company logo
1 of 121
Download to read offline
Chapter Four
Basics of PHP
1
We will discuss the following in this chapter:
• What is php?
• Features of php
• Setting up php with apache
• Basic php syntax
• Retrieve data from html forms
• Displaying Errors
• Using numbers and strings in
php
• Control structures
• Conditional and loop statements
• Introducing References
• References and arrays
• Functions
2
What is PHP?
●“PHP is a server-side scripting language designed specifically for the
Web. Within an HTML page, you can embed PHP code that will be
executed each time the page is visited. Your PHP code is interpreted at
the Web server and generates HTML or other output that the visitor will
see” (“PHP and MySQL Web Development”, Luke Welling and Laura
Thomson, SAMS).
●Since PHP is server side scripting language, we can integrate it with
MySQL databases.
●If we have client-side scripting language like Javascript, it can only be
executed on the browser.
Introduction
 Apache, MySQL, and PHP are all open source projects that can be installed on
a wide variety of platforms.
 open source refers to a program in which the source code is available to the
general public for users.i.e the source code is free. That makes it is easier for
SW developers and programmers to improve existing software and create new
programs.
 They are most popular on Linux. Although Windows - based Apache, MySQL
and PHP installations are becoming increasingly popular, especially for
developers.
4
How the AMP Pieces Work Together
 First AMP refers to Apache ,MySQL and PHP which works together to create
and delivery powerful and flexible web applications.(i.e. dynamic website)
 When a web site visitor(patron) comes to your web site, he or she requests a
particular page or resource.
1. Apache
• - Takes those specific requirements for Php.
• - Is a waiter that means gets requests a particular page or resource from patron
then takes those specific requests to php.
• - Apache ’ s main job is to listen to any incoming requests from a browser and
return an appropriate response.
5
2. PHP
-Contains php codes that is used to connect to the database. Then PHP
goes to MySQL to retrieve the data, to prepare and present the webpage
back to Apache. SQL-is a language designed for communicating with
databases.
-Is a chef.
3. MySQL -Is a stockroom(is a room which stocks of webpages or
resources are stored.)
-Receives the SQL requests and finds the information when the
information is located, the result is sent back to PHP that made the
request.
6
How the AMP Pieces Work Together (Cont’d…)
How to create pages using PHP?
Creating PHP Pages
PHP
 Is used to create dynamic webpages.
 Is emended in HTML.
 PHP programs are written using a text editor, such as Notepad,
Simple Text, or vi, just like HTML pages.
 Unlike HTML, PHP files end with a .php file 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.
7
1.2. Features of PHP
8
1.4. Basic PHP Syntax
PHP code is start with <?php and ends with ?>
Every PHP statements end with a semicolon (;).
PHP code save with .php extension.
PHP contain some HTML tag and PHP code.
You can place PHP code any where in your document.
PHP Comments:
 Single-Line Comment: by using double forward slashes ( // or #)
for one - line comments OR
 Multi-Lines Comment: /* to mark the start and */ to mark the end
of a comment that may extend over several lines.
9
 PHP code is denoted in the page with opening and closing
tags. As follows:-
<?php
echo “Hello World!”;ends with semicolon
echo $num; //echo is used to display a message on the page.
?>
 echo is used to send text (or variable values or a variety of
other things) to the browser.
 The echo statement basically outputs whatever it’s told to the
browser, whether it be HTML code, variable values or
plaintext.
10
The Rules of PHP Syntax (Cont’d…)
Creating Your First Program
/* enter the following program in your favorite text editor(notepad ,simple text editor, Dreamweaver or
whatever you choose .After you write save the program in .php file extention */
<html><head>
<title></title>
</head>
<body>
<?php
echo "well come to internet programming 2 course!”;
?>
</body>
</html>
Output:
well come to internet programming 2 course!
11
The Rules of PHP Syntax (Cont’d…)
User Defined and Predefined Variables
• Predefined variables are variables which are already developed by the
programmers who develops the PHP.
• These variables are not case sensitive and can be used with any letter
format.
• User defined variables are variables which can hold variable or
different value for different time in different place.
• These variables are declared using a dollar sign ‘$’.
• They are case sensitive. We have to use them as declared firstly.
• A variable name must start with a letter or underscore. It can not start
with numbers.
• Variable names can contain letters, numbers, and underscore, but not
special characters like -, +, &, *, %, #, etc.
12
Variable Types in PHP
Scope can be defined as the range of availability a variable has to the
program in which it is declared. PHP variables can one of four scope
types.
1. Local Variables
2. Function parameters
3. Global Variables
4. Static variables
13
Variable Types in PHP (Cont’d…)
Local Variables
A variable declared in a function is considered local. That is, it can be
referenced solely in that function. Any assignment outside of that function will
be considered an entirely different function from the one which is declared
entirely.
<?php
//VariableTypes
$x=4;
function AssignX(){
$x=0;
print "$x Inside function is $x";
}
AssignX();
print "$x Outside function is $x“;
?> 14
Variable Types in PHP (Cont’d…)
Function parameters
A function is a small unit of program which can take an input in the form of
parameters and does some processing and may return a value.
Function parameters are declared after the name of the function name and inside
parenthesis.
<?php
//Multiply a variable by 10 and return the value to the caller
function Multiply($value){
$value=$value*10;
return $value;
}
$retval= Multiply(10);
print "Return Value is $retval"
?> 15
Variable Types in PHP (Cont’d…)
Global Variables:
 In contrast to local variables global variables can be accessed outside the function that they are declared, at any
part of the program.
 However, in order to be modified, a global variable must be explicitly declared as global in the function that it is
to be modified. It can be accomplished by using a keyword “GLOBAL” in front of the global variable. Let us see
the following example:
<?php
//Increment on the global variable inside a function.
$globVar=29;
function add(){
GLOBAL $globVar;
$globVar++;
print"globVar is $globVar";
}
add();
?>
16
Variable Types in PHP (Cont’d…)
Static Variables:
 In contrast to the variables declared as function parameters, which are destroyed on the
functions exit, a static variable will not lose its value when the function exits and will still
hold that value should the function be called again.
 We have to use the keyword STATIC in front of the variable name. Look at the next example:
<?php
//static Variables in a program
function keep_track(){
STATIC $count =0;
$count++;
print "The value of count is $count. ";
}
keep_track();
keep_track();
keep_track();
keep_track();
?>
17
Variable Data Types in PHP
 A variable can hold different types of data in php. A variable do not know in
advance whether it will be used to store a number or a string.
 PHP does a good job of automatically converting types from one to another
when necessary.
 The value of a variable is the value which is most recently assigned.
 There are eight data types php. These are:
1. Integer
2. Double
3. Boolean These fives are simple types.
4. Null
5. String
6. Arrays These two types are compound types.
7. Objects
8. Resources
18
Variable Data Types in PHP (Cont’d…)
 To use or assign variable $ must be present before the name of the
variable. The assign operator is ‘=‘.
 There is no need to declare the type of the variable. The current stored
value produces an implicit type-casting of the variable. Example:
<?php
$var="name";
$literally='My $var will not print ';
print ($literally);
$literally="</br>my $var will print";
print($literally);
$var=5;
$var++;
print "</br>the value of var is $var";
?> 19
Constants in PHP
 A constant is a name or an identifier for a simple value.
 A constant can not be changed during execution of the script.
 By default a constant is case sensitive. By convention constant
identifiers are always uppercase. A constant name starts with letter, or
underscore followed by letters, numbers, or underscores.
 If you have defined a constant, its value can never be changed or
undefined.
 We have to use define() function to define a constant, and to retrieve
the value of the constant, we can simply write or specify its name.
20
Constants in PHP (Cont’d…)
 Unlike variables, there is no need to use $ for constants. We can also use the
function constant() to read the constant’s value if you wish to gain the
constant’s name dynamically.
constant() function
Used to return the constant’s value.
it is useful when you want to retrieve the constant’s value you do
not know its name, i.e. it is stored in a variable or returned by a
function.
<?php
Define("MINSIZE", 50);
echo MINSIZE;
echo"</br>";
echo constant("MINSIZE")#the same as the previous line
?>
21
1.6. Displaying Errors
• Error logs location is in php.ini file. It is Controlled by the built-in
function error_reporting(), which allows developers to control which
and how many errors will be shown in the application.
• The php.ini file has an error_reporting directive that will be set by this
function during run-time.
• To display errors in php, we can use these two statements.
error_reporting(E_ALL);//OR
ini_set('display_errors', 1);
22
1.7 String in PHP
In PHP string is a sequence of characters i.e. used to store and manipulate
text. There are 2 ways to specify string in PHP.
• single quoted
• double quoted
1. Single Quoted String
It is simple and easy way to specify string in php. We can create a string in
PHP by enclosing text in a single quote.
$str='Hello php I am single quote String';
echo $str;
23
1.7 String in PHP (Cont’d…)
2. Double Quoted String
In PHP, we can also specify string through enclosing text within double
quote.
$str="Hello php I am double quote String";
echo $str;
Using double quote String you can also display variable value on webpage
$num=10;
$str="Number is: $num";
echo $str;
24
1.7 String Functions in PHP
PHP have lots of predefined function which is used to perform operation with
string; some functions are strlen(), strrev(), strpos() etc.
1. PHP strlen() function
• strlen() function returns the length of a string. In below example strlen()
function is used to return length of "Hello world!"
Example:
echo strlen("Hello world!"); //will give “12”
2. PHP str_word_count() function
• str_word_count() function is used to count numbers of words in given
string.
Example:
echo str_word_count("Hello world!");// will print “2”
25
1.7 String Functions in PHP (Cont’d…)
3. PHP strrev() function
• strrev() function is used to revers any string.
Example:
echo strrev("Hello world!");//will print ” !dlrow olleH”
4. PHP strpos() function
• strpos() function is used to search specific position of any words in given string.
Example:
echo strpos("Hello world!", "world");//will print “6”
5. PHP str_replace() function
• str_replace function is used to replaces some characters with some other characters
in a string. In below example we replace world with Faiz.
Example:
echo str_replace("world", "Faiz", "Hello world!");
26
1.8. Control Structures
• Code execution can be grouped into categories as shown below
• Sequential – this one involves executing all the codes in the order in
which they have been written.
• Decision – this one involves making a choice given a number of
options. The code executed depends on the value of the condition.
• A control structure is a block of code that decides the execution path
of a program depending on the value of the set condition
27
1.9. Conditional and Loop Statements
1. For Loop in PHP
• The for loop is used when you know in advance how many times the script
should run. In php for loops execute a block of code specified number of
times.
for (initilation; condition; increment/decrement)
{
code to be executed;
}
Example:
for ($i = 0; $i <= 10; $i++) {
echo "$i <br>";}
28
1.9. Conditional and Loop Statements (Cont’d…)
2. While Loop in PHP
• The while loop is used when you don't know how many times the script should
run. while loops execute a block of code while the specified condition is true same
like for loop.
The Syntax is:
while(condition)
{ //code to be executed }
Example:
$n=0;
while($n<=10) {
echo "$n<br/>";
$n++; } 29
1.9. Conditional and Loop Statements (Cont’d…)
3. do..while Loop in PHP
do..while loop is used where you need to execute code at least once. The
do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.
The Syntax is:
do{ //code to be executed }
while(condition);
Example:
$x = 0;
do{ echo "$x &nbsp";
$x++;
} while ($x <= 10); 30
1.9. Conditional and Loop Statements (Cont’d…)
4. if else in PHP
• In php if else statement is used to test condition. If condition is true, execute the
code other wise control goes outside.
PHP If Statement
• PHP if statement is executed if condition is true.
The Syntax is:
if(condition){
//code to be executed }
Example:
$mark=93;
if($mark>=90)
{ echo "You have A+ grade."; } 31
1.9. Conditional and Loop Statements (Cont’d…)
PHP If-else Statement
• PHP if-else statement is executed whether condition is true or false
The Syntax is:
if(condition)
{ //code to be executed if true }
else
{//code to be executed if false }
Example:
$num=10;
if($num%2==0)
{ echo "$num is even number"; }
else
{ echo "$num is odd number"; } 32
1.9. Conditional and Loop Statements (Cont’d…)
5. Break Statement in PHP
• PHP break statement breaks the execution of current for, while, do-while,
switch and for-each loop. If you use break inside inner loop, it breaks the
execution of inner loop only..
The Syntax is:
statement;
break;
Example:
for($i=1;$i<=10;$i++)
{ echo "$i <br/>";
if($i==5)
{ break; }} 33
1.9. Conditional and Loop Statements (Cont’d…)
6. Switch Case in PHP
• In php switch statement is used to perform different actions based on different conditions.
In others word PHP switch statement is used to execute one statement from multiple
conditions. It works like PHP if-else-if statement.
The Syntax is:
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
34
Switch Case example
Example:
$num=5;
switch($num){
case 1:
echo("Monday");
break;
case 2:
echo("Tuesday");
break;
case 3:
echo("Wednasday");
break;
case 4:
echo("Thrusday");
break;
case 5:
echo("Friday");
break;
case 6:
echo("Sateday");
break;
case 7:
echo("Sunday");
break;
default:
echo("Please enter number between 1 to 7");
}
35
Arrays in PHP
In PHP Array is used to store multiple values in single variable. An
array is a special variable, which can hold more than one value at a time.
36
Arrays in PHP (Cont’d…)
In PHP, the array() function is used to create an array.
Types of Array in PHP
There are three types of array in php, which are given below.
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
1. Indexed Arrays
• The index can be assigned automatically (index always starts at 0), you can
see in below example;
<?php
$stud= array(“Abebe”, “Almaz”, “Kebede” );
Echo “CoSc students”.$stud[0].“,”. $stud[1].“,”. $stud[2].“.”;
?> 37
Array Example using for Loop
<?php
$student = array('Abebe', 'Almaz', 'Kebede');
$arrlength = count($student);//to know length of array
echo "List of students using for loop is:</br>";
for($i = 0; $i < $arrlength; $i++)
{
echo $student[$i];
echo "<br>";
}
?>
38
Arrays in PHP (Cont’d…)
2. Associative Arrays
• In this type of array; arrays use named keys that you assign to them.
Syntax:
$age=array('Abebe'=>10, 'Almaz'=>20, 'Kebede'=>30);
Print "Abebe is $age[Abebe] Years old.";
3. Multidimensional Arrays:
A multidimensional array is an array containing one or more arrays. For
a two-dimensional array you need two indices to select an element.
39
Arrays in PHP (Cont’d…)
Multidimensional Array Example:
$stud = array
(
array("Abebe",300,'A'),
array("Almaz",400,'B'),
array("Kebede",200,'C'),
);
echo $stud[0][0].": Marks: ".$stud[0][1].", Section: ".$stud[0][2].".<br>";
echo $stud[1][0].": Marks: ".$stud[1][1].", Section: ".$stud[1][2].".<br>";
echo $stud[2][0].": Marks: ".$stud[2][1].", Section: ".$stud[2][2].".<br>";
40
1.10. Introduction to References
References in PHP are a means to access the same variable content by different
names. PHP references are not treated as pre-dereferenced pointers, but as complete
aliases.
1) When treated as a variable containing a value, references behave as expected.
However, they are in fact objects that *reference* the original data.
$var = ‘comp’;
$ref1 =& $var; // new object that references $var
$ref2 =& $ref1; // references $var directly, not $ref1!!!!!
echo $ref1; // > comp
unset($ref1);
echo $ref1; // >Notice: Undefined variable: ref1
echo $ref2; // > comp
echo $var; // > comp
41
1.10. Introduction to References (Cont’d…)
1) 2) When accessed via reference, the original data will not be removed until *all*
references to it have been removed.
$var = ‘comp’;
$ref =& $var;
unset($var);
echo $var; // >Notice: Undefined variable: var
echo $ref; // > comp
• 3) To remove the original data without removing all references to it, simply set it to null.
$var = ‘comp’;
$ref =& $var;
$ref = NULL;
echo $var; // Value is NULL, so nothing prints
echo $ref; // Value is NULL, so nothing prints
42
1.11. References and Arrays
1. Array elements referencing scalar variables
$a = 1;
$b = 2;
$c = array(&$a, &$b);
$a = 3;
$b = 4;
echo "c: $c[0],$c[1]n"; // 3,4
$c[0] = 5;
$c[1] = 6;
echo "a,b: $a,$bn"; // 5,6
43
1.11. References and Arrays (Cont’d…)
2. Reference between arrays
$d = array(1,2);
$e =& $d;
$d[0] = 3;
$d[1] = 4;
echo "e: $e[0],$e[1]n"; // 3,4
$e[0] = 5;
$e[1] = 6;
echo "d: $d[0],$d[1]n"; // 5,6
$e = 7;
echo "d: $dn"; // 7 ( $d is no more an array, but an integer )
44
1.12. Functions
• PHP functions are similar to other programming languages.
• A function is a piece of code which takes one more input in the form
of parameter and does some processing and returns a value.
• fopen() and fread() functions are built-in functions but PHP gives you
option to create your own functions as well.
45
1.12. Functions (Cont’d…)
Creating PHP functions:
• Note that while creating a function its name should start with keyword
function and after the name of the function you should use a paired
parenthesis with or without parameters inside. Then, all the PHP codes
to be executed in that function should be put inside { and } braces.
function writeMessage() {
echo "Have a nice time!";
}
Calling a PHP Function:
writeMessage();
46
Functions with Parameters
 PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like.
 These parameters work like variables inside your function. Following example
takes two integer parameters and add them together and then print them.
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
47
1.12.1. Passing Arguments by Reference
• It is possible to pass arguments to functions by reference. This means
that a reference to the variable is manipulated by the function rather
than a copy of the variable's value.
• Any changes made to an argument in these cases will change the value
of the original variable.
• You can pass an argument by reference by adding an ampersand (&) to
the variable name in either the function call or the function definition.
48
Following example depicts both the cases.
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );//Original Value is 10
echo "Original Value is $orignum<br />";
addSix( $orignum ); Original Value is 16
echo "Original Value is $orignum<br />";
1.12.1. Passing Arguments by Reference (Cont’d…)
49
1.12.2. Functions: Returning by Reference
• A function can return a value using the return statement in conjunction with a
value or object. return stops the execution of the function and sends the value back
to the calling code.
• You can return more than one value from a function using return array(1,2,3,4).
• Following example takes two integer parameters and add them together and then
returns their sum to the calling program. Note that return keyword is used to
return a value from a function.
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function :
$return_value"; 50
Sessions and Cookies Management in PHP
• Cookie: is generally used to identify a user. Cookies are text files stored on the
client computer and they are kept of use tracking purpose. PHP transparently
supports HTTP cookies. Using PHP, you can both create and retrieve cookie
values.
51
Cookies Management
Cookies Management
There are three steps involved in identifying returning users;
• Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify the
user.
52
Create and use cookies
A cookie is created in php using setcookie() function. Here only the name parameter
is required. All other parameters are optional.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly); Create/Retrieve a
Cookie in PHP
The following example creates a cookie named "user" with the value “Almaz
Abebe".
The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is
available in entire website (otherwise, select the directory you prefer).
53
Create and use cookies (Cont’d…)
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:
<?php
$cookie_name = "user";
$cookie_value = " Almaz Abebe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
// 86400 = 1 day
?>
54
<!DOCTYPE html>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])){
echo "Cookie named '" . $cookie_name . "' is not set!";
} else { echo "Cookie '" . $cookie_name . "' is set!";
echo "Value is: " . $_COOKIE[$cookie_name];
}?>
<body>
<html>
Create and use cookies (Cont’d…)
55
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie()
function
<?php
$cookie_name = "user";
$cookie_value = “Yared Abera";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
56
Modify a Cookie Value(Cont’d…)
<!DOCTYPE html>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name]))
{ echo "Cookie named '" . $cookie_name . "' is not set!"; }
else
{ echo "Cookie '" . $cookie_name . "' is set!";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<body>
<html>
57
Delete a Cookie in PHP
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
<body>
<html>
58
Check Cookies are Enabled or not
To Check Cookies are Enabled or not, First Create a test cookie with the
setcookie() function, then count the $_COOKIE array variable;
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<!DOCTYPE html>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
}
Else {
echo "Cookies are disabled."; }
?>
<body> 59
What are sessions?
Session is used to store and pass information from one page to another
temporarily (until user close the website). In case of cookie, the
information are store in user computer but in case of session information
is not stored on the users computer.
60
Why use session in PHP?
• The web server does not know who you are or what you do, because
the HTTP address doesn't maintain state.
• Session variables solve this problem by storing user information to be
used across multiple pages (e.g. username, favorite color, etc).
• By default, session variables last until the user closes the browser.
• So; Session variables hold information about one single user, and are
available to all pages in one application.
61
Create and use sessions
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
Session_start() function in PHP
• PHP session_start() function is used to start the session.
• It starts a new or resumes existing session.
• It returns existing session if session is created already. If session is not
available, it creates and returns new session.
Syntax:
session_start ()
62
Create and use sessions (cont’d…)
Example:
session_start ()
Here we create a new web page with
name myapp1.php. Note that, the
session_start() function must be
declared at top of our php before
starting html tags.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] =
"green";
$_SESSION["favanimal"] =
"cat";
echo "Session variables are
set.";
?>
<body>
<html>
63
Get PHP Session Variable Values
Now we create new page myapp2.php for get previous page session information. All session
variable values are stored in the global $_SESSION variable
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
<body>
<html> 64
Get PHP Session Variable Values
Another way to get session:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
<body>
<html>
65
Modify a PHP Session Variable
To change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
<body>
<html> 66
Destroy Session in PHP
To remove all global session variables and destroy the session, use session_unset()
and session_destroy() method.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
<body>
<html> 67
Difference Between Session and Cookie (Cont’d…)
Cookies Sessions
Cookies are stored in browser as text file format. Sessions are stored in server side.
It can store limited amount of data. It can store unlimited amount of data
It only allows 4kb[4096bytes]. It can hold multiple variable in sessions.
It is not holding the multiple variable in cookies. It is holding the multiple variable in sessions.
we can access the cookies values easily. So it is less
secure.
We cannot access the session values easily, so it is more
secure.
We have to set the cookie time to expire the cookie.
using session_destory(), we we will destroyed the
sessions.
The setcookie() function must appear before the
<html> tag.
The session_start() function must be the very first thing
in your document. Before any HTML tags. 68
Files and Directories
In this section we’ll discuss on:-
• Files and Directories
1.Opening files Writing to a file
2.Locking a file Reading a file content
3.Handling file upload
4.Working with directories
69
1. Opening Files or Creating a file
• Files are opened using fopen command in php. The command takes
two parameters: the file to be opened and the mode in which to open
the file.
• The function returns a file pointer if successful , otherwise, zero
(false). Files are opened using fopen for writing or reading.
$fp = fopen(“myfile.txt”, “w”);
70
2. Writing to a file
• The fwrite function is used to write a string, or part of a string to a file.
• The function takes three parameters, the file handle, the string to write,
and the number of bytes to write.
• If the number of bytes is omitted, the whole string is written to the file.
If you want the lines to appear on separate lines in the file, use the n
character.
• Note: Windows requires a carriage return character as well as a new
line character, so if you're using Windows, terminate the string with
rn.
• The following example logs the visitor to a file, then displays all the
entries in the file.
71
<?php
$fp="file.txt";
$handle= fopen($fp,'w');
Echo "file created successfully";
$data="This is my data.";
fwrite($handle, $data);
$read= fopen($fp,'r’);
$buffer=fread($read , filesize($fp));
Echo $buffer;
?>
2. Writing to a file (Cont’d…)
72
File Modes
• The following table shows the different modes a file can be opened
73
Closing a File
• The fclose function is used to close a file when you are finished with
it.
fclose($fp);
74
2. Reading a File Content
• You can read from files opened in r, r+, w+, and a+ mode. The feof function
is used to determine if the end of file is true.
• if ( feof($fp) )
• echo "End of file<br>";
• The feof function can be used in a while loop, to read from the file until the
end of file is encountered. A line at a time can be read with the fgets
function:
while( !feof($fp) ) {
// Reads one line at a time, up to 254 characters. Each line ends with a
newline.
// If the length argument is omitted, PHP defaults to a length of 1024.
$myline = fgets($fp, 255);
echo $myline;
}
75
2. Reading a File Content (Cont’d…)
You can read in a single character at a time from a file using the fgetc
function:
while( !feof($fp) ) {
// Reads one character at a time from the file.
$ch = fgetc($fp);
echo $ch;
}
76
• You can read in an entire file with the fread function. It reads a number of bytes from a file,
up to the end of the file (whichever comes first). The filesize function returns the size of the
file in bytes, and can be used with the fread function, as in the following example.
$listFile = "myfile.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
echo "$buffer<br>n";
fclose($fp)
• You can also use the file function to read the entire contents of a file into an array instead of
opening the file with fopen:
• $array = file(‘filename.txt’);
• Each array element contains one line from the file, where each line is terminated by a
newline.
2. Reading a File Content (Cont’d…)
77
3. Locking a File from Reading a File Content
• flock ( resource fp, Lock operation);
• PHP supports a portable way of locking complete files in an advisory way
(which means all accessing programs have to use the same way of locking or it
will not work).
• If there is a possibility that more than one process could write to a file at the
same time then the file should be locked.
• flock() operates on fp which must be an open file pointer. operation is one of
the following:
To acquire a shared lock (reader), set operation to LOCK_SH
To acquire an exclusive lock (writer), set operation to LOCK_EX
To release a lock (shared or exclusive), set operation to LOCK_UN
If you don't want flock() to block while locking, add LOCK_NB to
LOCK_SH or LOCK_EX
78
3. Locking a File from Reading a File Content (Cont’d…)
• When obtaining a lock, the process may block. That is, if the file is already locked, it
will wait until it gets the lock to continue execution.
• flock() allows you to perform a simple reader/writer model which can be used on
virtually every platform (including most Unix derivatives and even Windows).
• flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be
acquired).
79
• Here is a script that writes to a
log file with the fputs function
and then displays the log file’s
contents:
$pos = "myfile2.txt";
$fp = fopen($pos, 'a');
flock($fp, LOCK_EX); // get lock
fwrite($fp, "</br>THis is the new
line added");
flock($fp, LOCK_UN); // release
lock
$fp=fopen($pos,'r');
$fr= fread($fp, filesize($pos));
print $fr;
//readfile($pos);
fclose($fp);
3. Locking a File from Reading a File Content (Cont’d…)
80
4. Handling File Upload
• A PHP script can be used with HTML form to allow users to upload
files to the server.
• Initially files are uploaded into a temporary directory and then relocated
to the target destination by a PHP script.
• The process of uploading a file follows the following steps.
1. The user opens the page containing a HTML form featuring a text
files, a browse button and a submit button.
2. The user clicks the browse button and selects a file to upload from
the local PC.
3. The full path to the selected file appears in the text filed then the
user clicks the submit button.
4. The selected file is sent to the temporary directory on the server.
81
<html>
<body>
<form action="file_upload.php" method="post"
enctype="multipart/form-data">
<input type="file" name = "fileToUpload" id="fileToUpload">
<input type= "submit" name= "upload" value="Upload">
</form>
</body>
</html>
4. Handling File Upload (Cont’d…)
82
<?php
if(isset($_POST['fileToUpload']))
{
$filetoupload = $_POST['fileToUpload'];
$dir="Uploads/";
$dir_file= $dir.basename($_FILES[$filetoupload]);
$uploadOk=1;
$imageFileType= strtolower(pathinfo($dir_file,PATHINFO_EXTENSION));
//check whether the file uploaded is a fake or a actual image
4. Handling File Upload (Cont’d…)
83
if(isset($_POST["upload"]))
{
$check= getimagesize($_FILES[$filetoupload]["tmp_name"]);
if($check!==false)
{
echo"file is an image-".$check["mime"].".";
$uploadOk=1;
}
else {
echo"file is not an image";
$uploadOk=0;
}
} }
?>
4. Handling File Upload (Cont’d…)
84
PHP script explained:
• $dir = "uploads/" - specifies the directory where the file is going to be
placed
• $dir_file specifies the path of the file to be uploaded
• $uploadOk=1 is not used yet (will be used later)
• $imageFileType holds the file extension of the file (in lower case)
• Next, check if the image file is an actual image or a fake image
• Note: You will need to create a new directory called "uploads" in the
directory where "upload.php" file resides. The uploaded files will be
saved there.
4. Handling File Upload (Cont’d…)
85
Check if File Already Exists
• Now we can add some restrictions.
• First, we will check if the file already exists in the "uploads" folder. If
it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
4. Handling File Upload (Cont’d…)
86
Limit File Size
• The file input field in our HTML form above is named "fileToUpload".
• Now, we want to check the size of the file. If the file is larger than 500KB,
an error message is displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
4. Handling File Upload (Cont’d…)
87
Limit File Type
• The code below only allows users to upload JPG, JPEG, PNG, and GIF files.
All other file types gives an error message before setting $uploadOk to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
4. Handling File Upload (Cont’d…)
88
5. Working with Directories
• The opendir function returns a directory handle;
• closedir closes a directory;
• readdir reads a directory entry.
$mydir=".";
$myDirectory = opendir($mydir);
// use the current directory
while($entryname = readdir($myDirectory))
{
print $entryname;
print " = ". filesize($entryname)."</br>";
// the filesize function returns the file size in bytes
}
closedir($myDirectory); 89
• The is_dir function tests if a filename refers to a directory:
if(is_dir($filename))
echo $filename . “ is a directory”;
• The is_file function determines if a filename refers to a file:
if(is_file($filename))
echo $filename . “ is a file”;
• The is_readable function returns TRUE if the file exists and it is readable,
otherwise it returns false.
if(is_readable($filename))
echo $filename . “ is readable”;
5. Working with Directories
90
The is_writable function determines whether the server will allow you
to write data to the file before you attempt to open it:
if(is_writable(‘../quotes.txt’)) {
// attempt to open the file and write to it
} else {
echo ‘The file is not writable’;
}
• Note: there are many more file functions. Please refer to PHP
documentation for an exhaustive list.
5. Working with Directories
91
OOP concept in PHP
1. Creating a class
2. Creating an object Inheritance
3. What is PEAR? Installation of PEAR
4. Installation of a PEAR package
5. Using a PEAR package
92
 Classes, which are the "blueprints" for an object and are the actual
code that defines the properties and methods.
 Objects, which are running instances of a class and contain all the
internal data and state information needed for your application to
function.
 Encapsulation, which is the capability of an object to protect access
to its internal data
 Inheritance, which is the ability to define a class of one kind as
being a sub-type of a different kind of class (much the same way a
square is a kind of rectangle).
Object Oriented Concept
93
• Object-oriented programming (OOP) refers to the creation of reusable
software object-types / classes that can be efficiently developed and
easily incorporated into multiple programs.
• In OOP an object represents an entity in the real world (a student, a desk,
a button, a file, a text input area, a loan, a web page, a shopping cart).
• An OOP program = a collection of objects that interact to solve a task /
problem.
Object-Oriented Programming
94
• Objects are self-contained, with data and operations that pertain to
them assembled into a single entity.
• In procedural programming data and operations are separate → this methodology
requires sending data to methods!
• Objects have:
• Identity; ex: 2 “OK” buttons, same attributes → separate handle vars
• State → a set of attributes (aka member variables, properties, data fields) =
properties or variables that relate to / describe the object, with their current values.
• Behavior → a set of operations (aka methods) = actions or functions that the
object can perform to modify itself – its state, or perform for some external effect
/ result.
95
Object-Oriented Programming (Cont’d…)
• Encapsulation (aka data hiding) central in OOP
• = access to data within an object is available only via the object’s operations
(= known as the interface of the object)
• = internal aspects of objects are hidden, wrapped as a birthday present is
wrapped by colorful paper 
• Advantages:
• objects can be used as black-boxes, if their interface is known;
• implementation of an interface can be changed without a cascading effect to
other parts of the project → if the interface doesn’t change
96
Object-Oriented Programming (Cont’d…)
• Classes are constructs that define objects of the same type.
A class is a template or blueprint that defines what an object’s data and
methods will be.
Objects of a class have:
• Same operations, behaving the same way
• Same attributes representing the same features, but values of those attributes (= state)
can vary from object to object
• An object is an instance of a class.
(terms objects and instances are used interchangeably)
• Any number of instances of a class can be created.
97
Object-Oriented Programming (Cont’d…)
• Small Web projects
• Consist of web scripts designed and written using an ad-hoc approach; a function-
oriented, procedural methodology
• Large Web software projects
• Need a properly thought-out development methodology – OOP →
• OO approach can help manage project complexity, increase code reusability, reduce
costs.
• OO analysis and design process = decide what object types, what hidden
data/operations and wrapper operations for each object type
• UML – as tool in OO design, to allow to describe classes and class relationships
OOP in Web Programming
98
• A minimal class definition:
class classname { // classname is a PHP identifier!
// the class body = data & function member definitions
}
• Attributes
• are declared as variables within the class definition using keywords
that match their visibility: public, private, or protected.
(Recall that PHP doesn't otherwise have declarations of variables → data
member declarations against the nature of PHP?)
• Operations
• are created by declaring functions within the class definition.
Creating Classes in PHP
99
• Constructor = function used to create/initialize an object of the class
• Declared as a function with a special name:
function __construct (param_list) { … }
• Usually performs initialization tasks: e.g. sets attributes to appropriate starting
values
• Called automatically when an object is created
• A default no-argument constructor is provided by the compiler only if a
constructor function is not explicitly declared in the class
• Cannot be overloaded (= 2+ constructors for a class); if you need a variable # of
parameters, use flexible parameter lists…
Creating Classes in PHP
100
• Destructor = opposite of constructor
• Declared as a function with a special name, cannot take parameters
function __destruct () { … }
• Allows some functionality that will be automatically executed just
before an object is destroyed
An object is removed when there is no reference variable/handle left to it
Usually during the "script shutdown phase", which is typically right before the
execution of the PHP script finishes
• A default destructor provided by the compiler only if a destructor
function is not explicitly declared in the class
101
Creating Classes in PHP (Cont’d…)
• Create an object of a class = a particular individual that is a
member of the class by using the new keyword:
$newClassVariable = new ClassName(actual_param_list);
Notes:
• Scope for PHP classes is global (program script level), as it is for functions
• Class names are case insensitive as are functions
• PHP 5 allows you to define multiple classes in a single program script
• The PHP parser reads classes into memory immediately after functions  class
construction does not fail because a class is not previously defined in the program scope.
Instantiating Classes
102
• From operations within the class, class’s data / methods can be accessed /
called by using:
• $this = a variable that refers to the current instance of the class, and can be used
only in the definition of the class, including the constructor & destructor
• The pointer operator -> (similar to Java’s object member access operator “.” )
• class Test {
public $attribute;
function Func ($val) {
$this -> attribute = $val; // $this is mandatory!
} // if omitted, $attribute is treated
} // as a local var in the function
Using Data/Method Members
103
No $ sign here
• From outside the class, accessible (as determined by access modifiers) data and
methods are accessed through a variable holding an instance of the class, by using
the same pointer operator.
class Test {
public $attribute; //$attribute is a property or an
attribute or a variable
}
$t = new Test(); // Test() is a constructor function
$t->attribute = “value”;//instantiating by object variable $t
echo $t->attribute;
104
Using Data/Method Members (Cont’d…)
Protecting Access to Member Variables (1)
 There are three different levels of visibility that a member variable or method
can have :
 Public
▪ members are accessible to any and all code
 Private
▪ members are only accessible to the class itself
 Protected
▪ members are available to the class itself, and to classes that inherit from it
▪ Note:
Public is the default visibility level for any member variables or functions that do
not explicitly set one, but it is good practice to always explicitly state the visibility
of all the members of the class. 105
Class Constants
 It is possible to define constant values on a per-class basis remaining
the same and unchangeable.
 Constants differ from normal variables in that you don't use the $
symbol to declare or use them
 The value must be a constant expression, not (for example) a
variable, a property, a result of a mathematical operation, or a
function call
106
Class Constants (Cont’d...)
<?php
class MyClass
{
const constant = 'constant value';
function showConstant() {
echo self::constant . "n";
}
}
echo MyClass::constant . "n";
?>
107
Static Keyword
• Declaring class properties or methods as static makes them accessible
without needing an instantiation of the class.
• A property declared as static can not be accessed with an instantiated
class object
108
<?php
class Stud
{
public static $my_static =’stud';
public function staticValue() {
return self::$my_static;
}
}
class Bar extends Stud
{
public function studStatic() {
return parent::$my_static;
}
}
print Stud::$my_static . "n";
$stud = new Stud();
print $stud->staticValue() . "n";
print $stud->my_static. "n";
// Undefined "Property" my_static
print $stud::$my_static . "n";
$classname = 'Stud';
print $classname::$my_static . "n";
// As of PHP 5.3.0
print Bar::$my_static . "n";
$bar = new Bar();
print $bar->studStatic() . "n";
?>
Static Keyword (Cont’d…)
109
Inheritance
• There are many benefits of inheritance with PHP, the most common is
simplifying and reducing instances of redundant code.
110
class hewan
{
protected $jml_kaki;
protected $warna_kulit;
function __construct()
{
}
function berpindah()
{
echo "Saya berpindah";
}
function makan()
{
echo "Saya makan";
}
}
Inheritance (Cont’d…)
111
class kucing extends hewan
{
function berpindah()
{
echo "Saya merangkak
dengan 4 kaki";
}
}
class burung extends hewan
{
protected $sayap;
function berpindah()
{
echo "Saya terbang";
}
function makan()
{
echo "Saya makan dengan
mematuk";
}
}
class monyet extends hewan
{
}
Inheritance (Cont’d…)
112
Abstract Classes and Interfaces
Interfaces are supertypes that specify method headers without
implementations
• Cannot be instantiated;
• cannot contain function bodies or fields
• Enables polymorphism between subtypes without sharing
implementation code
Abstract classes are like interfaces, but you can specify fields,
constructors, methods
• Also cannot be instantiated; enables polymorphism
with sharing of implementation code
113
//The following is a syntax of abstract classes
abstract class ClassName {
abstract public function name(parameters);
...
}
Abstract Classes and Interfaces (Cont’d…)
//The following is a syntax of Interfaces
interface InterfaceName {
public function name(parameters);
public function name(parameters);
...
}
class ClassName implements InterfaceName { ...
114
3. What is PEAR?
• PEAR stands for the PHP Extension and Application Repository, and
it’s a big collection of high - quality, open - source code packages that
you can freely download and use in your own applications.
• If you have written your applications in a modular way, using classes
and functions to breakdown them into specific chunks of functionality,
you should find that you can reuse those classes or functions across
applications.
115
• Each package is a separately maintained class, or set of classes, for
achieving a specific goal.
• At the time of writing, more than 500 packages are available, covering
everything from database access through to authentication, file
handling, date formatting, networking and email, and even weather
forecasting.
• You can browse the full list at http://pear.php.net/packages.php.
• Though many packages can function independently, a package often
requires one or more other packages to do its job. These other
packages are known as dependencies of the main package.
3. What is PEAR? (Cont’d…)
116
• Before starting on any new project, it’s a good idea to check the PEAR
repository to see if there are any packages you can incorporate into
your application.
• You may well find that half of your job has already been done for you,
saving you a huge amount of time.
3. What is PEAR? (Cont’d…)
117
4. Installation of a PEAR package
To use a PEAR package, you need to install it on the same Web server as your
PHP installation, so that your PHP scripts can access it.
Installing a PEAR package is easy, thanks to the PEAR package manager that
comes bundled with your PHP installation.
The first thing to do, though, is find the name of the package that you need to
install. You can do this in one or more of the following ways:
 You can browse packages by category at http://pear.php.net/packages.php
 You can search package names and descriptions at
http://pear.php.net/search.php
 You can view a full list of packages ordered by popularity — most
downloaded first — at http://pear.php.net/package-stats.php
118
• Once you’ ve found a package that you want to install, it ’ s time to run
the PEAR package manager to install it. First, though, it ’ s a good
idea to test that the package manager is available and working.
• If your PHP installation is on Ubuntu or Mac OS X, the PEAR
package manager is already installed and available.
• On Windows you need to set up the package manager first.
4. Installation of a PEAR package (Cont’d…)
119
5. Using a PEAR package
• The PEAR packages are usually installed in folders in your PEAR path:
C:xamppcgi-binphpphp5.2.6PEAR or similar if you’re running xampp
Server. (You should better use the latest version).
• You should also find a ‘doc’ folder inside this path. Most PEAR packages
come with documentation and examples, which you’ll find inside this folder
when the package has been installed.
• In addition, the PEAR Web site contains documentation for the majority of
packages; to access it, find the package page and click the Documentation
link in the page.
• Depending on your setup and operating system, you may need to have
access to the administrator or root user to install PEAR packages. This is
because the PEAR path is often only writable by a user with administrative
rights.
120
• In that folder, you should have a file called go - pear.bat. Run this batch file by
typing its name and pressing Enter: go-pear.bat
• The batch file will ask you a few questions about configuring PEAR. Usually
you can just press Enter to accept the defaults.
• The batch program then installs and sets up PEAR, displaying a long message.
• As instructed by the batch file ’ s output, it ’ s a good idea to open Windows
Explorer and double- click the PEAR_ENV.reg registry file in the folder to set
up various Windows environment variables.
• This will make life easier when installing and using PEAR packages.
5. Using a PEAR package (Cont’d…)
121

More Related Content

What's hot (20)

Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handling
 
php
phpphp
php
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
 
Javascript
JavascriptJavascript
Javascript
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
PHP
PHPPHP
PHP
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
Php basics
Php basicsPhp basics
Php basics
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 

Similar to Basics of PHP Chapter

Similar to Basics of PHP Chapter (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php notes
Php notesPhp notes
Php notes
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
 
chapter Two Server-side Script lang.pptx
chapter  Two Server-side Script lang.pptxchapter  Two Server-side Script lang.pptx
chapter Two Server-side Script lang.pptx
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 
phptutorial
phptutorialphptutorial
phptutorial
 
Php tutorial from_beginner_to_master
Php tutorial from_beginner_to_masterPhp tutorial from_beginner_to_master
Php tutorial from_beginner_to_master
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Introduction to PHP.ppt
Introduction to PHP.pptIntroduction to PHP.ppt
Introduction to PHP.ppt
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 

Recently uploaded

How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...akbard9823
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 

Recently uploaded (20)

How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
 
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 

Basics of PHP Chapter

  • 2. We will discuss the following in this chapter: • What is php? • Features of php • Setting up php with apache • Basic php syntax • Retrieve data from html forms • Displaying Errors • Using numbers and strings in php • Control structures • Conditional and loop statements • Introducing References • References and arrays • Functions 2
  • 3. What is PHP? ●“PHP is a server-side scripting language designed specifically for the Web. Within an HTML page, you can embed PHP code that will be executed each time the page is visited. Your PHP code is interpreted at the Web server and generates HTML or other output that the visitor will see” (“PHP and MySQL Web Development”, Luke Welling and Laura Thomson, SAMS). ●Since PHP is server side scripting language, we can integrate it with MySQL databases. ●If we have client-side scripting language like Javascript, it can only be executed on the browser.
  • 4. Introduction  Apache, MySQL, and PHP are all open source projects that can be installed on a wide variety of platforms.  open source refers to a program in which the source code is available to the general public for users.i.e the source code is free. That makes it is easier for SW developers and programmers to improve existing software and create new programs.  They are most popular on Linux. Although Windows - based Apache, MySQL and PHP installations are becoming increasingly popular, especially for developers. 4
  • 5. How the AMP Pieces Work Together  First AMP refers to Apache ,MySQL and PHP which works together to create and delivery powerful and flexible web applications.(i.e. dynamic website)  When a web site visitor(patron) comes to your web site, he or she requests a particular page or resource. 1. Apache • - Takes those specific requirements for Php. • - Is a waiter that means gets requests a particular page or resource from patron then takes those specific requests to php. • - Apache ’ s main job is to listen to any incoming requests from a browser and return an appropriate response. 5
  • 6. 2. PHP -Contains php codes that is used to connect to the database. Then PHP goes to MySQL to retrieve the data, to prepare and present the webpage back to Apache. SQL-is a language designed for communicating with databases. -Is a chef. 3. MySQL -Is a stockroom(is a room which stocks of webpages or resources are stored.) -Receives the SQL requests and finds the information when the information is located, the result is sent back to PHP that made the request. 6 How the AMP Pieces Work Together (Cont’d…)
  • 7. How to create pages using PHP? Creating PHP Pages PHP  Is used to create dynamic webpages.  Is emended in HTML.  PHP programs are written using a text editor, such as Notepad, Simple Text, or vi, just like HTML pages.  Unlike HTML, PHP files end with a .php file 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. 7
  • 9. 1.4. Basic PHP Syntax PHP code is start with <?php and ends with ?> Every PHP statements end with a semicolon (;). PHP code save with .php extension. PHP contain some HTML tag and PHP code. You can place PHP code any where in your document. PHP Comments:  Single-Line Comment: by using double forward slashes ( // or #) for one - line comments OR  Multi-Lines Comment: /* to mark the start and */ to mark the end of a comment that may extend over several lines. 9
  • 10.  PHP code is denoted in the page with opening and closing tags. As follows:- <?php echo “Hello World!”;ends with semicolon echo $num; //echo is used to display a message on the page. ?>  echo is used to send text (or variable values or a variety of other things) to the browser.  The echo statement basically outputs whatever it’s told to the browser, whether it be HTML code, variable values or plaintext. 10 The Rules of PHP Syntax (Cont’d…)
  • 11. Creating Your First Program /* enter the following program in your favorite text editor(notepad ,simple text editor, Dreamweaver or whatever you choose .After you write save the program in .php file extention */ <html><head> <title></title> </head> <body> <?php echo "well come to internet programming 2 course!”; ?> </body> </html> Output: well come to internet programming 2 course! 11 The Rules of PHP Syntax (Cont’d…)
  • 12. User Defined and Predefined Variables • Predefined variables are variables which are already developed by the programmers who develops the PHP. • These variables are not case sensitive and can be used with any letter format. • User defined variables are variables which can hold variable or different value for different time in different place. • These variables are declared using a dollar sign ‘$’. • They are case sensitive. We have to use them as declared firstly. • A variable name must start with a letter or underscore. It can not start with numbers. • Variable names can contain letters, numbers, and underscore, but not special characters like -, +, &, *, %, #, etc. 12
  • 13. Variable Types in PHP Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can one of four scope types. 1. Local Variables 2. Function parameters 3. Global Variables 4. Static variables 13
  • 14. Variable Types in PHP (Cont’d…) Local Variables A variable declared in a function is considered local. That is, it can be referenced solely in that function. Any assignment outside of that function will be considered an entirely different function from the one which is declared entirely. <?php //VariableTypes $x=4; function AssignX(){ $x=0; print "$x Inside function is $x"; } AssignX(); print "$x Outside function is $x“; ?> 14
  • 15. Variable Types in PHP (Cont’d…) Function parameters A function is a small unit of program which can take an input in the form of parameters and does some processing and may return a value. Function parameters are declared after the name of the function name and inside parenthesis. <?php //Multiply a variable by 10 and return the value to the caller function Multiply($value){ $value=$value*10; return $value; } $retval= Multiply(10); print "Return Value is $retval" ?> 15
  • 16. Variable Types in PHP (Cont’d…) Global Variables:  In contrast to local variables global variables can be accessed outside the function that they are declared, at any part of the program.  However, in order to be modified, a global variable must be explicitly declared as global in the function that it is to be modified. It can be accomplished by using a keyword “GLOBAL” in front of the global variable. Let us see the following example: <?php //Increment on the global variable inside a function. $globVar=29; function add(){ GLOBAL $globVar; $globVar++; print"globVar is $globVar"; } add(); ?> 16
  • 17. Variable Types in PHP (Cont’d…) Static Variables:  In contrast to the variables declared as function parameters, which are destroyed on the functions exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.  We have to use the keyword STATIC in front of the variable name. Look at the next example: <?php //static Variables in a program function keep_track(){ STATIC $count =0; $count++; print "The value of count is $count. "; } keep_track(); keep_track(); keep_track(); keep_track(); ?> 17
  • 18. Variable Data Types in PHP  A variable can hold different types of data in php. A variable do not know in advance whether it will be used to store a number or a string.  PHP does a good job of automatically converting types from one to another when necessary.  The value of a variable is the value which is most recently assigned.  There are eight data types php. These are: 1. Integer 2. Double 3. Boolean These fives are simple types. 4. Null 5. String 6. Arrays These two types are compound types. 7. Objects 8. Resources 18
  • 19. Variable Data Types in PHP (Cont’d…)  To use or assign variable $ must be present before the name of the variable. The assign operator is ‘=‘.  There is no need to declare the type of the variable. The current stored value produces an implicit type-casting of the variable. Example: <?php $var="name"; $literally='My $var will not print '; print ($literally); $literally="</br>my $var will print"; print($literally); $var=5; $var++; print "</br>the value of var is $var"; ?> 19
  • 20. Constants in PHP  A constant is a name or an identifier for a simple value.  A constant can not be changed during execution of the script.  By default a constant is case sensitive. By convention constant identifiers are always uppercase. A constant name starts with letter, or underscore followed by letters, numbers, or underscores.  If you have defined a constant, its value can never be changed or undefined.  We have to use define() function to define a constant, and to retrieve the value of the constant, we can simply write or specify its name. 20
  • 21. Constants in PHP (Cont’d…)  Unlike variables, there is no need to use $ for constants. We can also use the function constant() to read the constant’s value if you wish to gain the constant’s name dynamically. constant() function Used to return the constant’s value. it is useful when you want to retrieve the constant’s value you do not know its name, i.e. it is stored in a variable or returned by a function. <?php Define("MINSIZE", 50); echo MINSIZE; echo"</br>"; echo constant("MINSIZE")#the same as the previous line ?> 21
  • 22. 1.6. Displaying Errors • Error logs location is in php.ini file. It is Controlled by the built-in function error_reporting(), which allows developers to control which and how many errors will be shown in the application. • The php.ini file has an error_reporting directive that will be set by this function during run-time. • To display errors in php, we can use these two statements. error_reporting(E_ALL);//OR ini_set('display_errors', 1); 22
  • 23. 1.7 String in PHP In PHP string is a sequence of characters i.e. used to store and manipulate text. There are 2 ways to specify string in PHP. • single quoted • double quoted 1. Single Quoted String It is simple and easy way to specify string in php. We can create a string in PHP by enclosing text in a single quote. $str='Hello php I am single quote String'; echo $str; 23
  • 24. 1.7 String in PHP (Cont’d…) 2. Double Quoted String In PHP, we can also specify string through enclosing text within double quote. $str="Hello php I am double quote String"; echo $str; Using double quote String you can also display variable value on webpage $num=10; $str="Number is: $num"; echo $str; 24
  • 25. 1.7 String Functions in PHP PHP have lots of predefined function which is used to perform operation with string; some functions are strlen(), strrev(), strpos() etc. 1. PHP strlen() function • strlen() function returns the length of a string. In below example strlen() function is used to return length of "Hello world!" Example: echo strlen("Hello world!"); //will give “12” 2. PHP str_word_count() function • str_word_count() function is used to count numbers of words in given string. Example: echo str_word_count("Hello world!");// will print “2” 25
  • 26. 1.7 String Functions in PHP (Cont’d…) 3. PHP strrev() function • strrev() function is used to revers any string. Example: echo strrev("Hello world!");//will print ” !dlrow olleH” 4. PHP strpos() function • strpos() function is used to search specific position of any words in given string. Example: echo strpos("Hello world!", "world");//will print “6” 5. PHP str_replace() function • str_replace function is used to replaces some characters with some other characters in a string. In below example we replace world with Faiz. Example: echo str_replace("world", "Faiz", "Hello world!"); 26
  • 27. 1.8. Control Structures • Code execution can be grouped into categories as shown below • Sequential – this one involves executing all the codes in the order in which they have been written. • Decision – this one involves making a choice given a number of options. The code executed depends on the value of the condition. • A control structure is a block of code that decides the execution path of a program depending on the value of the set condition 27
  • 28. 1.9. Conditional and Loop Statements 1. For Loop in PHP • The for loop is used when you know in advance how many times the script should run. In php for loops execute a block of code specified number of times. for (initilation; condition; increment/decrement) { code to be executed; } Example: for ($i = 0; $i <= 10; $i++) { echo "$i <br>";} 28
  • 29. 1.9. Conditional and Loop Statements (Cont’d…) 2. While Loop in PHP • The while loop is used when you don't know how many times the script should run. while loops execute a block of code while the specified condition is true same like for loop. The Syntax is: while(condition) { //code to be executed } Example: $n=0; while($n<=10) { echo "$n<br/>"; $n++; } 29
  • 30. 1.9. Conditional and Loop Statements (Cont’d…) 3. do..while Loop in PHP do..while loop is used where you need to execute code at least once. The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. The Syntax is: do{ //code to be executed } while(condition); Example: $x = 0; do{ echo "$x &nbsp"; $x++; } while ($x <= 10); 30
  • 31. 1.9. Conditional and Loop Statements (Cont’d…) 4. if else in PHP • In php if else statement is used to test condition. If condition is true, execute the code other wise control goes outside. PHP If Statement • PHP if statement is executed if condition is true. The Syntax is: if(condition){ //code to be executed } Example: $mark=93; if($mark>=90) { echo "You have A+ grade."; } 31
  • 32. 1.9. Conditional and Loop Statements (Cont’d…) PHP If-else Statement • PHP if-else statement is executed whether condition is true or false The Syntax is: if(condition) { //code to be executed if true } else {//code to be executed if false } Example: $num=10; if($num%2==0) { echo "$num is even number"; } else { echo "$num is odd number"; } 32
  • 33. 1.9. Conditional and Loop Statements (Cont’d…) 5. Break Statement in PHP • PHP break statement breaks the execution of current for, while, do-while, switch and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.. The Syntax is: statement; break; Example: for($i=1;$i<=10;$i++) { echo "$i <br/>"; if($i==5) { break; }} 33
  • 34. 1.9. Conditional and Loop Statements (Cont’d…) 6. Switch Case in PHP • In php switch statement is used to perform different actions based on different conditions. In others word PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement. The Syntax is: switch(expression){ case value1: //code to be executed break; case value2: //code to be executed break; ...... default: code to be executed if all cases are not matched; } 34
  • 35. Switch Case example Example: $num=5; switch($num){ case 1: echo("Monday"); break; case 2: echo("Tuesday"); break; case 3: echo("Wednasday"); break; case 4: echo("Thrusday"); break; case 5: echo("Friday"); break; case 6: echo("Sateday"); break; case 7: echo("Sunday"); break; default: echo("Please enter number between 1 to 7"); } 35
  • 36. Arrays in PHP In PHP Array is used to store multiple values in single variable. An array is a special variable, which can hold more than one value at a time. 36
  • 37. Arrays in PHP (Cont’d…) In PHP, the array() function is used to create an array. Types of Array in PHP There are three types of array in php, which are given below. • Indexed arrays - Arrays with a numeric index • Associative arrays - Arrays with named keys • Multidimensional arrays - Arrays containing one or more arrays 1. Indexed Arrays • The index can be assigned automatically (index always starts at 0), you can see in below example; <?php $stud= array(“Abebe”, “Almaz”, “Kebede” ); Echo “CoSc students”.$stud[0].“,”. $stud[1].“,”. $stud[2].“.”; ?> 37
  • 38. Array Example using for Loop <?php $student = array('Abebe', 'Almaz', 'Kebede'); $arrlength = count($student);//to know length of array echo "List of students using for loop is:</br>"; for($i = 0; $i < $arrlength; $i++) { echo $student[$i]; echo "<br>"; } ?> 38
  • 39. Arrays in PHP (Cont’d…) 2. Associative Arrays • In this type of array; arrays use named keys that you assign to them. Syntax: $age=array('Abebe'=>10, 'Almaz'=>20, 'Kebede'=>30); Print "Abebe is $age[Abebe] Years old."; 3. Multidimensional Arrays: A multidimensional array is an array containing one or more arrays. For a two-dimensional array you need two indices to select an element. 39
  • 40. Arrays in PHP (Cont’d…) Multidimensional Array Example: $stud = array ( array("Abebe",300,'A'), array("Almaz",400,'B'), array("Kebede",200,'C'), ); echo $stud[0][0].": Marks: ".$stud[0][1].", Section: ".$stud[0][2].".<br>"; echo $stud[1][0].": Marks: ".$stud[1][1].", Section: ".$stud[1][2].".<br>"; echo $stud[2][0].": Marks: ".$stud[2][1].", Section: ".$stud[2][2].".<br>"; 40
  • 41. 1.10. Introduction to References References in PHP are a means to access the same variable content by different names. PHP references are not treated as pre-dereferenced pointers, but as complete aliases. 1) When treated as a variable containing a value, references behave as expected. However, they are in fact objects that *reference* the original data. $var = ‘comp’; $ref1 =& $var; // new object that references $var $ref2 =& $ref1; // references $var directly, not $ref1!!!!! echo $ref1; // > comp unset($ref1); echo $ref1; // >Notice: Undefined variable: ref1 echo $ref2; // > comp echo $var; // > comp 41
  • 42. 1.10. Introduction to References (Cont’d…) 1) 2) When accessed via reference, the original data will not be removed until *all* references to it have been removed. $var = ‘comp’; $ref =& $var; unset($var); echo $var; // >Notice: Undefined variable: var echo $ref; // > comp • 3) To remove the original data without removing all references to it, simply set it to null. $var = ‘comp’; $ref =& $var; $ref = NULL; echo $var; // Value is NULL, so nothing prints echo $ref; // Value is NULL, so nothing prints 42
  • 43. 1.11. References and Arrays 1. Array elements referencing scalar variables $a = 1; $b = 2; $c = array(&$a, &$b); $a = 3; $b = 4; echo "c: $c[0],$c[1]n"; // 3,4 $c[0] = 5; $c[1] = 6; echo "a,b: $a,$bn"; // 5,6 43
  • 44. 1.11. References and Arrays (Cont’d…) 2. Reference between arrays $d = array(1,2); $e =& $d; $d[0] = 3; $d[1] = 4; echo "e: $e[0],$e[1]n"; // 3,4 $e[0] = 5; $e[1] = 6; echo "d: $d[0],$d[1]n"; // 5,6 $e = 7; echo "d: $dn"; // 7 ( $d is no more an array, but an integer ) 44
  • 45. 1.12. Functions • PHP functions are similar to other programming languages. • A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. • fopen() and fread() functions are built-in functions but PHP gives you option to create your own functions as well. 45
  • 46. 1.12. Functions (Cont’d…) Creating PHP functions: • Note that while creating a function its name should start with keyword function and after the name of the function you should use a paired parenthesis with or without parameters inside. Then, all the PHP codes to be executed in that function should be put inside { and } braces. function writeMessage() { echo "Have a nice time!"; } Calling a PHP Function: writeMessage(); 46
  • 47. Functions with Parameters  PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like.  These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them. function addFunction($num1, $num2) { $sum = $num1 + $num2; echo "Sum of the two numbers is : $sum"; } addFunction(10, 20); 47
  • 48. 1.12.1. Passing Arguments by Reference • It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value. • Any changes made to an argument in these cases will change the value of the original variable. • You can pass an argument by reference by adding an ampersand (&) to the variable name in either the function call or the function definition. 48
  • 49. Following example depicts both the cases. function addFive($num) { $num += 5; } function addSix(&$num) { $num += 6; } $orignum = 10; addFive( $orignum );//Original Value is 10 echo "Original Value is $orignum<br />"; addSix( $orignum ); Original Value is 16 echo "Original Value is $orignum<br />"; 1.12.1. Passing Arguments by Reference (Cont’d…) 49
  • 50. 1.12.2. Functions: Returning by Reference • A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. • You can return more than one value from a function using return array(1,2,3,4). • Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function. function addFunction($num1, $num2) { $sum = $num1 + $num2; return $sum; } $return_value = addFunction(10, 20); echo "Returned value from the function : $return_value"; 50
  • 51. Sessions and Cookies Management in PHP • Cookie: is generally used to identify a user. Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies. Using PHP, you can both create and retrieve cookie values. 51 Cookies Management
  • 52. Cookies Management There are three steps involved in identifying returning users; • Server script sends a set of cookies to the browser. For example name, age, or identification number etc. • Browser stores this information on local machine for future use. • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. 52
  • 53. Create and use cookies A cookie is created in php using setcookie() function. Here only the name parameter is required. All other parameters are optional. Syntax: setcookie(name, value, expire, path, domain, secure, httponly); Create/Retrieve a Cookie in PHP The following example creates a cookie named "user" with the value “Almaz Abebe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). 53
  • 54. Create and use cookies (Cont’d…) We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set: <?php $cookie_name = "user"; $cookie_value = " Almaz Abebe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?> 54
  • 55. <!DOCTYPE html> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])){ echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!"; echo "Value is: " . $_COOKIE[$cookie_name]; }?> <body> <html> Create and use cookies (Cont’d…) 55
  • 56. Modify a Cookie Value To modify a cookie, just set (again) the cookie using the setcookie() function <?php $cookie_name = "user"; $cookie_value = “Yared Abera"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?> 56
  • 57. Modify a Cookie Value(Cont’d…) <!DOCTYPE html> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> <body> <html> 57
  • 58. Delete a Cookie in PHP <?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600); ?> <!DOCTYPE html> <html> <body> <?php echo "Cookie 'user' is deleted."; ?> <body> <html> 58
  • 59. Check Cookies are Enabled or not To Check Cookies are Enabled or not, First Create a test cookie with the setcookie() function, then count the $_COOKIE array variable; <?php setcookie("test_cookie", "test", time() + 3600, '/'); ?> <!DOCTYPE html> <html> <body> <?php if(count($_COOKIE) > 0) { echo "Cookies are enabled."; } Else { echo "Cookies are disabled."; } ?> <body> 59
  • 60. What are sessions? Session is used to store and pass information from one page to another temporarily (until user close the website). In case of cookie, the information are store in user computer but in case of session information is not stored on the users computer. 60
  • 61. Why use session in PHP? • The web server does not know who you are or what you do, because the HTTP address doesn't maintain state. • Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). • By default, session variables last until the user closes the browser. • So; Session variables hold information about one single user, and are available to all pages in one application. 61
  • 62. Create and use sessions • A session is started with the session_start() function. • Session variables are set with the PHP global variable: $_SESSION. Session_start() function in PHP • PHP session_start() function is used to start the session. • It starts a new or resumes existing session. • It returns existing session if session is created already. If session is not available, it creates and returns new session. Syntax: session_start () 62
  • 63. Create and use sessions (cont’d…) Example: session_start () Here we create a new web page with name myapp1.php. Note that, the session_start() function must be declared at top of our php before starting html tags. <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> <body> <html> 63
  • 64. Get PHP Session Variable Values Now we create new page myapp2.php for get previous page session information. All session variable values are stored in the global $_SESSION variable <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . "."; ?> <body> <html> 64
  • 65. Get PHP Session Variable Values Another way to get session: <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php print_r($_SESSION); ?> <body> <html> 65
  • 66. Modify a PHP Session Variable To change a session variable, just overwrite it: <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // to change a session variable, just overwrite it $_SESSION["favcolor"] = "yellow"; print_r($_SESSION); ?> <body> <html> 66
  • 67. Destroy Session in PHP To remove all global session variables and destroy the session, use session_unset() and session_destroy() method. <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> <body> <html> 67
  • 68. Difference Between Session and Cookie (Cont’d…) Cookies Sessions Cookies are stored in browser as text file format. Sessions are stored in server side. It can store limited amount of data. It can store unlimited amount of data It only allows 4kb[4096bytes]. It can hold multiple variable in sessions. It is not holding the multiple variable in cookies. It is holding the multiple variable in sessions. we can access the cookies values easily. So it is less secure. We cannot access the session values easily, so it is more secure. We have to set the cookie time to expire the cookie. using session_destory(), we we will destroyed the sessions. The setcookie() function must appear before the <html> tag. The session_start() function must be the very first thing in your document. Before any HTML tags. 68
  • 69. Files and Directories In this section we’ll discuss on:- • Files and Directories 1.Opening files Writing to a file 2.Locking a file Reading a file content 3.Handling file upload 4.Working with directories 69
  • 70. 1. Opening Files or Creating a file • Files are opened using fopen command in php. The command takes two parameters: the file to be opened and the mode in which to open the file. • The function returns a file pointer if successful , otherwise, zero (false). Files are opened using fopen for writing or reading. $fp = fopen(“myfile.txt”, “w”); 70
  • 71. 2. Writing to a file • The fwrite function is used to write a string, or part of a string to a file. • The function takes three parameters, the file handle, the string to write, and the number of bytes to write. • If the number of bytes is omitted, the whole string is written to the file. If you want the lines to appear on separate lines in the file, use the n character. • Note: Windows requires a carriage return character as well as a new line character, so if you're using Windows, terminate the string with rn. • The following example logs the visitor to a file, then displays all the entries in the file. 71
  • 72. <?php $fp="file.txt"; $handle= fopen($fp,'w'); Echo "file created successfully"; $data="This is my data."; fwrite($handle, $data); $read= fopen($fp,'r’); $buffer=fread($read , filesize($fp)); Echo $buffer; ?> 2. Writing to a file (Cont’d…) 72
  • 73. File Modes • The following table shows the different modes a file can be opened 73
  • 74. Closing a File • The fclose function is used to close a file when you are finished with it. fclose($fp); 74
  • 75. 2. Reading a File Content • You can read from files opened in r, r+, w+, and a+ mode. The feof function is used to determine if the end of file is true. • if ( feof($fp) ) • echo "End of file<br>"; • The feof function can be used in a while loop, to read from the file until the end of file is encountered. A line at a time can be read with the fgets function: while( !feof($fp) ) { // Reads one line at a time, up to 254 characters. Each line ends with a newline. // If the length argument is omitted, PHP defaults to a length of 1024. $myline = fgets($fp, 255); echo $myline; } 75
  • 76. 2. Reading a File Content (Cont’d…) You can read in a single character at a time from a file using the fgetc function: while( !feof($fp) ) { // Reads one character at a time from the file. $ch = fgetc($fp); echo $ch; } 76
  • 77. • You can read in an entire file with the fread function. It reads a number of bytes from a file, up to the end of the file (whichever comes first). The filesize function returns the size of the file in bytes, and can be used with the fread function, as in the following example. $listFile = "myfile.txt"; if (!($fp = fopen($listFile, "r"))) exit("Unable to open the input file, $listFile."); $buffer = fread($fp, filesize($listFile)); echo "$buffer<br>n"; fclose($fp) • You can also use the file function to read the entire contents of a file into an array instead of opening the file with fopen: • $array = file(‘filename.txt’); • Each array element contains one line from the file, where each line is terminated by a newline. 2. Reading a File Content (Cont’d…) 77
  • 78. 3. Locking a File from Reading a File Content • flock ( resource fp, Lock operation); • PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). • If there is a possibility that more than one process could write to a file at the same time then the file should be locked. • flock() operates on fp which must be an open file pointer. operation is one of the following: To acquire a shared lock (reader), set operation to LOCK_SH To acquire an exclusive lock (writer), set operation to LOCK_EX To release a lock (shared or exclusive), set operation to LOCK_UN If you don't want flock() to block while locking, add LOCK_NB to LOCK_SH or LOCK_EX 78
  • 79. 3. Locking a File from Reading a File Content (Cont’d…) • When obtaining a lock, the process may block. That is, if the file is already locked, it will wait until it gets the lock to continue execution. • flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). • flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired). 79
  • 80. • Here is a script that writes to a log file with the fputs function and then displays the log file’s contents: $pos = "myfile2.txt"; $fp = fopen($pos, 'a'); flock($fp, LOCK_EX); // get lock fwrite($fp, "</br>THis is the new line added"); flock($fp, LOCK_UN); // release lock $fp=fopen($pos,'r'); $fr= fread($fp, filesize($pos)); print $fr; //readfile($pos); fclose($fp); 3. Locking a File from Reading a File Content (Cont’d…) 80
  • 81. 4. Handling File Upload • A PHP script can be used with HTML form to allow users to upload files to the server. • Initially files are uploaded into a temporary directory and then relocated to the target destination by a PHP script. • The process of uploading a file follows the following steps. 1. The user opens the page containing a HTML form featuring a text files, a browse button and a submit button. 2. The user clicks the browse button and selects a file to upload from the local PC. 3. The full path to the selected file appears in the text filed then the user clicks the submit button. 4. The selected file is sent to the temporary directory on the server. 81
  • 82. <html> <body> <form action="file_upload.php" method="post" enctype="multipart/form-data"> <input type="file" name = "fileToUpload" id="fileToUpload"> <input type= "submit" name= "upload" value="Upload"> </form> </body> </html> 4. Handling File Upload (Cont’d…) 82
  • 83. <?php if(isset($_POST['fileToUpload'])) { $filetoupload = $_POST['fileToUpload']; $dir="Uploads/"; $dir_file= $dir.basename($_FILES[$filetoupload]); $uploadOk=1; $imageFileType= strtolower(pathinfo($dir_file,PATHINFO_EXTENSION)); //check whether the file uploaded is a fake or a actual image 4. Handling File Upload (Cont’d…) 83
  • 84. if(isset($_POST["upload"])) { $check= getimagesize($_FILES[$filetoupload]["tmp_name"]); if($check!==false) { echo"file is an image-".$check["mime"]."."; $uploadOk=1; } else { echo"file is not an image"; $uploadOk=0; } } } ?> 4. Handling File Upload (Cont’d…) 84
  • 85. PHP script explained: • $dir = "uploads/" - specifies the directory where the file is going to be placed • $dir_file specifies the path of the file to be uploaded • $uploadOk=1 is not used yet (will be used later) • $imageFileType holds the file extension of the file (in lower case) • Next, check if the image file is an actual image or a fake image • Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files will be saved there. 4. Handling File Upload (Cont’d…) 85
  • 86. Check if File Already Exists • Now we can add some restrictions. • First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk is set to 0: // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } 4. Handling File Upload (Cont’d…) 86
  • 87. Limit File Size • The file input field in our HTML form above is named "fileToUpload". • Now, we want to check the size of the file. If the file is larger than 500KB, an error message is displayed, and $uploadOk is set to 0: // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } 4. Handling File Upload (Cont’d…) 87
  • 88. Limit File Type • The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0: // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } 4. Handling File Upload (Cont’d…) 88
  • 89. 5. Working with Directories • The opendir function returns a directory handle; • closedir closes a directory; • readdir reads a directory entry. $mydir="."; $myDirectory = opendir($mydir); // use the current directory while($entryname = readdir($myDirectory)) { print $entryname; print " = ". filesize($entryname)."</br>"; // the filesize function returns the file size in bytes } closedir($myDirectory); 89
  • 90. • The is_dir function tests if a filename refers to a directory: if(is_dir($filename)) echo $filename . “ is a directory”; • The is_file function determines if a filename refers to a file: if(is_file($filename)) echo $filename . “ is a file”; • The is_readable function returns TRUE if the file exists and it is readable, otherwise it returns false. if(is_readable($filename)) echo $filename . “ is readable”; 5. Working with Directories 90
  • 91. The is_writable function determines whether the server will allow you to write data to the file before you attempt to open it: if(is_writable(‘../quotes.txt’)) { // attempt to open the file and write to it } else { echo ‘The file is not writable’; } • Note: there are many more file functions. Please refer to PHP documentation for an exhaustive list. 5. Working with Directories 91
  • 92. OOP concept in PHP 1. Creating a class 2. Creating an object Inheritance 3. What is PEAR? Installation of PEAR 4. Installation of a PEAR package 5. Using a PEAR package 92
  • 93.  Classes, which are the "blueprints" for an object and are the actual code that defines the properties and methods.  Objects, which are running instances of a class and contain all the internal data and state information needed for your application to function.  Encapsulation, which is the capability of an object to protect access to its internal data  Inheritance, which is the ability to define a class of one kind as being a sub-type of a different kind of class (much the same way a square is a kind of rectangle). Object Oriented Concept 93
  • 94. • Object-oriented programming (OOP) refers to the creation of reusable software object-types / classes that can be efficiently developed and easily incorporated into multiple programs. • In OOP an object represents an entity in the real world (a student, a desk, a button, a file, a text input area, a loan, a web page, a shopping cart). • An OOP program = a collection of objects that interact to solve a task / problem. Object-Oriented Programming 94
  • 95. • Objects are self-contained, with data and operations that pertain to them assembled into a single entity. • In procedural programming data and operations are separate → this methodology requires sending data to methods! • Objects have: • Identity; ex: 2 “OK” buttons, same attributes → separate handle vars • State → a set of attributes (aka member variables, properties, data fields) = properties or variables that relate to / describe the object, with their current values. • Behavior → a set of operations (aka methods) = actions or functions that the object can perform to modify itself – its state, or perform for some external effect / result. 95 Object-Oriented Programming (Cont’d…)
  • 96. • Encapsulation (aka data hiding) central in OOP • = access to data within an object is available only via the object’s operations (= known as the interface of the object) • = internal aspects of objects are hidden, wrapped as a birthday present is wrapped by colorful paper  • Advantages: • objects can be used as black-boxes, if their interface is known; • implementation of an interface can be changed without a cascading effect to other parts of the project → if the interface doesn’t change 96 Object-Oriented Programming (Cont’d…)
  • 97. • Classes are constructs that define objects of the same type. A class is a template or blueprint that defines what an object’s data and methods will be. Objects of a class have: • Same operations, behaving the same way • Same attributes representing the same features, but values of those attributes (= state) can vary from object to object • An object is an instance of a class. (terms objects and instances are used interchangeably) • Any number of instances of a class can be created. 97 Object-Oriented Programming (Cont’d…)
  • 98. • Small Web projects • Consist of web scripts designed and written using an ad-hoc approach; a function- oriented, procedural methodology • Large Web software projects • Need a properly thought-out development methodology – OOP → • OO approach can help manage project complexity, increase code reusability, reduce costs. • OO analysis and design process = decide what object types, what hidden data/operations and wrapper operations for each object type • UML – as tool in OO design, to allow to describe classes and class relationships OOP in Web Programming 98
  • 99. • A minimal class definition: class classname { // classname is a PHP identifier! // the class body = data & function member definitions } • Attributes • are declared as variables within the class definition using keywords that match their visibility: public, private, or protected. (Recall that PHP doesn't otherwise have declarations of variables → data member declarations against the nature of PHP?) • Operations • are created by declaring functions within the class definition. Creating Classes in PHP 99
  • 100. • Constructor = function used to create/initialize an object of the class • Declared as a function with a special name: function __construct (param_list) { … } • Usually performs initialization tasks: e.g. sets attributes to appropriate starting values • Called automatically when an object is created • A default no-argument constructor is provided by the compiler only if a constructor function is not explicitly declared in the class • Cannot be overloaded (= 2+ constructors for a class); if you need a variable # of parameters, use flexible parameter lists… Creating Classes in PHP 100
  • 101. • Destructor = opposite of constructor • Declared as a function with a special name, cannot take parameters function __destruct () { … } • Allows some functionality that will be automatically executed just before an object is destroyed An object is removed when there is no reference variable/handle left to it Usually during the "script shutdown phase", which is typically right before the execution of the PHP script finishes • A default destructor provided by the compiler only if a destructor function is not explicitly declared in the class 101 Creating Classes in PHP (Cont’d…)
  • 102. • Create an object of a class = a particular individual that is a member of the class by using the new keyword: $newClassVariable = new ClassName(actual_param_list); Notes: • Scope for PHP classes is global (program script level), as it is for functions • Class names are case insensitive as are functions • PHP 5 allows you to define multiple classes in a single program script • The PHP parser reads classes into memory immediately after functions  class construction does not fail because a class is not previously defined in the program scope. Instantiating Classes 102
  • 103. • From operations within the class, class’s data / methods can be accessed / called by using: • $this = a variable that refers to the current instance of the class, and can be used only in the definition of the class, including the constructor & destructor • The pointer operator -> (similar to Java’s object member access operator “.” ) • class Test { public $attribute; function Func ($val) { $this -> attribute = $val; // $this is mandatory! } // if omitted, $attribute is treated } // as a local var in the function Using Data/Method Members 103 No $ sign here
  • 104. • From outside the class, accessible (as determined by access modifiers) data and methods are accessed through a variable holding an instance of the class, by using the same pointer operator. class Test { public $attribute; //$attribute is a property or an attribute or a variable } $t = new Test(); // Test() is a constructor function $t->attribute = “value”;//instantiating by object variable $t echo $t->attribute; 104 Using Data/Method Members (Cont’d…)
  • 105. Protecting Access to Member Variables (1)  There are three different levels of visibility that a member variable or method can have :  Public ▪ members are accessible to any and all code  Private ▪ members are only accessible to the class itself  Protected ▪ members are available to the class itself, and to classes that inherit from it ▪ Note: Public is the default visibility level for any member variables or functions that do not explicitly set one, but it is good practice to always explicitly state the visibility of all the members of the class. 105
  • 106. Class Constants  It is possible to define constant values on a per-class basis remaining the same and unchangeable.  Constants differ from normal variables in that you don't use the $ symbol to declare or use them  The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call 106
  • 107. Class Constants (Cont’d...) <?php class MyClass { const constant = 'constant value'; function showConstant() { echo self::constant . "n"; } } echo MyClass::constant . "n"; ?> 107
  • 108. Static Keyword • Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. • A property declared as static can not be accessed with an instantiated class object 108
  • 109. <?php class Stud { public static $my_static =’stud'; public function staticValue() { return self::$my_static; } } class Bar extends Stud { public function studStatic() { return parent::$my_static; } } print Stud::$my_static . "n"; $stud = new Stud(); print $stud->staticValue() . "n"; print $stud->my_static. "n"; // Undefined "Property" my_static print $stud::$my_static . "n"; $classname = 'Stud'; print $classname::$my_static . "n"; // As of PHP 5.3.0 print Bar::$my_static . "n"; $bar = new Bar(); print $bar->studStatic() . "n"; ?> Static Keyword (Cont’d…) 109
  • 110. Inheritance • There are many benefits of inheritance with PHP, the most common is simplifying and reducing instances of redundant code. 110
  • 111. class hewan { protected $jml_kaki; protected $warna_kulit; function __construct() { } function berpindah() { echo "Saya berpindah"; } function makan() { echo "Saya makan"; } } Inheritance (Cont’d…) 111
  • 112. class kucing extends hewan { function berpindah() { echo "Saya merangkak dengan 4 kaki"; } } class burung extends hewan { protected $sayap; function berpindah() { echo "Saya terbang"; } function makan() { echo "Saya makan dengan mematuk"; } } class monyet extends hewan { } Inheritance (Cont’d…) 112
  • 113. Abstract Classes and Interfaces Interfaces are supertypes that specify method headers without implementations • Cannot be instantiated; • cannot contain function bodies or fields • Enables polymorphism between subtypes without sharing implementation code Abstract classes are like interfaces, but you can specify fields, constructors, methods • Also cannot be instantiated; enables polymorphism with sharing of implementation code 113
  • 114. //The following is a syntax of abstract classes abstract class ClassName { abstract public function name(parameters); ... } Abstract Classes and Interfaces (Cont’d…) //The following is a syntax of Interfaces interface InterfaceName { public function name(parameters); public function name(parameters); ... } class ClassName implements InterfaceName { ... 114
  • 115. 3. What is PEAR? • PEAR stands for the PHP Extension and Application Repository, and it’s a big collection of high - quality, open - source code packages that you can freely download and use in your own applications. • If you have written your applications in a modular way, using classes and functions to breakdown them into specific chunks of functionality, you should find that you can reuse those classes or functions across applications. 115
  • 116. • Each package is a separately maintained class, or set of classes, for achieving a specific goal. • At the time of writing, more than 500 packages are available, covering everything from database access through to authentication, file handling, date formatting, networking and email, and even weather forecasting. • You can browse the full list at http://pear.php.net/packages.php. • Though many packages can function independently, a package often requires one or more other packages to do its job. These other packages are known as dependencies of the main package. 3. What is PEAR? (Cont’d…) 116
  • 117. • Before starting on any new project, it’s a good idea to check the PEAR repository to see if there are any packages you can incorporate into your application. • You may well find that half of your job has already been done for you, saving you a huge amount of time. 3. What is PEAR? (Cont’d…) 117
  • 118. 4. Installation of a PEAR package To use a PEAR package, you need to install it on the same Web server as your PHP installation, so that your PHP scripts can access it. Installing a PEAR package is easy, thanks to the PEAR package manager that comes bundled with your PHP installation. The first thing to do, though, is find the name of the package that you need to install. You can do this in one or more of the following ways:  You can browse packages by category at http://pear.php.net/packages.php  You can search package names and descriptions at http://pear.php.net/search.php  You can view a full list of packages ordered by popularity — most downloaded first — at http://pear.php.net/package-stats.php 118
  • 119. • Once you’ ve found a package that you want to install, it ’ s time to run the PEAR package manager to install it. First, though, it ’ s a good idea to test that the package manager is available and working. • If your PHP installation is on Ubuntu or Mac OS X, the PEAR package manager is already installed and available. • On Windows you need to set up the package manager first. 4. Installation of a PEAR package (Cont’d…) 119
  • 120. 5. Using a PEAR package • The PEAR packages are usually installed in folders in your PEAR path: C:xamppcgi-binphpphp5.2.6PEAR or similar if you’re running xampp Server. (You should better use the latest version). • You should also find a ‘doc’ folder inside this path. Most PEAR packages come with documentation and examples, which you’ll find inside this folder when the package has been installed. • In addition, the PEAR Web site contains documentation for the majority of packages; to access it, find the package page and click the Documentation link in the page. • Depending on your setup and operating system, you may need to have access to the administrator or root user to install PEAR packages. This is because the PEAR path is often only writable by a user with administrative rights. 120
  • 121. • In that folder, you should have a file called go - pear.bat. Run this batch file by typing its name and pressing Enter: go-pear.bat • The batch file will ask you a few questions about configuring PEAR. Usually you can just press Enter to accept the defaults. • The batch program then installs and sets up PEAR, displaying a long message. • As instructed by the batch file ’ s output, it ’ s a good idea to open Windows Explorer and double- click the PEAR_ENV.reg registry file in the folder to set up various Windows environment variables. • This will make life easier when installing and using PEAR packages. 5. Using a PEAR package (Cont’d…) 121