[go: up one dir, main page]

0% found this document useful (0 votes)
2 views102 pages

CHAPTER Five Server Side

Chapter Five discusses server-side programs, focusing on web server configuration and the Common Gateway Interface (CGI) for generating dynamic web content. It introduces PHP as a popular server-side scripting language, detailing its capabilities, syntax, and data types. The chapter also covers the structure of CGI programs, their execution process, and the advantages of using server-side scripting over traditional CGI methods.

Uploaded by

dawitkindu611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views102 pages

CHAPTER Five Server Side

Chapter Five discusses server-side programs, focusing on web server configuration and the Common Gateway Interface (CGI) for generating dynamic web content. It introduces PHP as a popular server-side scripting language, detailing its capabilities, syntax, and data types. The chapter also covers the structure of CGI programs, their execution process, and the advantages of using server-side scripting over traditional CGI methods.

Uploaded by

dawitkindu611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 102

Chapter Five

Server-Side Programs
Web server Configuration
Common Gateway Interface(CGI)
PHP
Outline
 Apache Web Server Configuration
 The Common Gateway Interface (CGI)
 Introduction to Server-Side Scripts
 PHP
 Session Controls
Server-Side Programs
 How to generate a dynamic content to web
pages or web applications?
 Solution
 Using Server-Side Programs
 Common Gateway Interface (CGI)
 Using any programming languages
 Server-Side Script Languages
 php , asp(active server pages, jsp(java server
pages) …
Introduction to CGI
 In order to deliver dynamic content, we need to extend the
abilities of the web server so that it can do more than merely
send static web pages in response to client requests. The
common gateway interface (CGI) provides a mechanism to do
this
 Common Gateway Interface
 Is a standard environment for web servers to interface with
executable programs installed on a server that generate web
pages dynamically. Such programs are known as CGI scripts or
simply CGIs
 A CGI script can be written in any language that allows it to be
executed (e.g., C/C++, Fortran, PERL, TCL, Visual Basic,
AppleScript, Python, and Unix shells), but by far, the most
common language for CGI scripting is PERL, followed by C/C++.
How CGI Works?
1. When serving static web pages, the server is normally asked for
a file that has a .htm or .html extension. If we wish to serve a
dynamic page the extension would be different, for example .cgi,
.pl, or .php, .jsp, .asp
2. If a request comes in with one of these extensions the web
server knows to pass the request to the CGI which then
interprets it correctly and executes the script in the particular
scripting language
3. Once the script has finished executing the CGI then passes the
output back to the web server to be delivered as a response to
the client request
How CGI Works?
Introduction to CGI…
 Output of cgi programs could be an html
document, image, file …
 Most servers expect CGI programs to reside in a
special directory, usually called cgi-bin, and/or to
have a certain file extension like .cgi, so that the
server knows to execute the program rather than
simply serving the CGI program as a raw data
 CGI programs communicate with the server
using STDIN/STDOUT and environment
variables
Creating a CGI program
 What do we need to create a CGI program?
 A programming language
 A web server configured for CGI
 A web server machine that can execute a program
written using the programming language, you used
 Write your cgi program in some text editor
 Save the executable program with an extension
of .cgi in the directory cgi-bin which tells the web
server to execute the .cgi program instead before
sending it to the client
How to access data send from
the client to the server
 CGI uses environment variables to send
your program its parameters.
 For GET submissions, cgi programs read
users form input from the environment
variable QUERY_STRING. For POST
submissions, from STDIN.
Structure of CGI programs
 The first output of a cgi program should be
the content type of the response file like
“Content-type: text/html”
 On the next line display blank line, to
STDOUT
 Then start writing your instructions
 Everything that should be included in the
response HTML page should be printed to
STDOUT
CGI program in C example One
#include <stdio.h>
void main() {
cout<<"Content-type: text/html\n\n" ;
/**Print the HTML response page to STDOUT. **/ cout<<"<html>\
n" ;
cout<<"<head><title>CGI Output</title></head>\n" ;
cout<<"<body>\n" ;
cout<<"<h1>Hello, world.</h1>\n" ;
cout<<"</body>\n" ; cout<<"</html>\n" ;
exit(0) ;
}
CGI program in C example Two
<form action="http://www.cs.tut.fi/cgi-bin/mult.cgi">
Multiplicand 1: <input type=“text” name="m">
Multiplicand 2: <input type=“text” name="n">
<input type="submit" value="Multiply!“> </form>
#include <stdio.h>
#include <stdlib.h> mult.cgi
int main(void) {
char *data; long m,n;
printf("%s%c%c\n",
"Content-Type:text/html;”,13,10);
printf("<TITLE>Multiplication results</TITLE>\n");
printf("<H3>Multiplication results</H3>\n");
data = getenv("QUERY_STRING");
printf("<P>The product of %ld and %ld is
Drawbacks of cgi Programming
 The fundamental architectural
issue with CGI-BIN based systems
is that
Each time a CGI script is executed, a
new process is started. For busy Web
sites, this can slow down the server
noticeably
Server Slide Scripts
 Server-side scripting is often used to provide a
customized interface for visitors
 Run on the server side
 Source code is hidden from visitors
 Can interact with database and other data sources like
file
 Examples
 PHP, JSP, ASP.net …
 Programs written in the above languages don’t require to
spawn(generate) a new process every time a page is
requested
Variables example
<?php
$x = 5; // global scope
function myTest()
{
$y = 5; // local scope
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
// using y outside the function will generate an error
echo "<p>Variable y outside function is: $y</p>";
?>
Introduction to PHP
 What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open-source scripting language
 PHP is free to download and use
 What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript,
and PHP code
 PHP code are executed on the server, and the result
is returned to the browser as plain HTML
 PHP files have extension ".php"
Introduction to PHP cont’d…
 What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write and delete files on the server
 PHP can process form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access (Session Management)
 PHP can encrypt data
 With PHP you are not limited to output HTML. You can output
images, PDF files, and even Flash movies. You can also output
any text, such as XHTML and XML.
Introduction to PHP cont’d…
 Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X,
etc.)
 PHP is compatible with almost all servers used today (Apache,
IIS(Internet Information Service), etc.)
 PHP supports a wide range of databases
 PHP is free
 PHP is easy to learn and runs efficiently on the server side
 Setting Up PHP
 Install a web server
 Install PHP
 Install a database, such as MySQL
PHP Example
<html> Output: resulting
<html> PHP file HTML
<head> <head>
<title> PHP Introduction <title> PHP Introduction
</title> </title>
</head> </head>
<body>
<body>
This is HTML! <br />
<?php
This is HTML! <br />
echo 'This is PHP! <br />’; This is HTML! <br />
?> </body>
A PHP script is executed on the server, and
</body> </html>
the plain HTML result is sent back to the
</html> browser
Introduction to PHP cont’d…
 Basic PHP Syntax
 A PHP script can be placed anywhere in the document
 A PHP script starts with <?php and ends with ?>:
 PHP statements end with a semicolon (;)
 Comments
 // This is a single-line comment
 # This is also a single-line comment
 /* multi line comment*/
 PHP is case sensitive (variables not PHP keywords, functions,
class names, class functions)
 PHP is whitespace insensitive
Variables
 In PHP, a variable starts with the $ sign, followed by
the name of the variable:
 $txt = "Hello world!";
 $x = 5;
 $y = 10.5;
 PHP has no command for declaring a variable. It is
created the moment you first assign a value to it
 Variable name can only contain letter, number or
underscore and it cannot start with a number
 PHP is a loosely-typed language
 Do not need to declare the type of a variable
 Type can change throughout the program
PHP Variables Scope
 PHP has three different variable scopes:
 Global
 A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function
 The global Keyword
 The global keyword is used to access a global variable
from within a function.
 Local
 A variable declared within a function has a LOCAL SCOPE
and can
only be accessed within that function
 Static
 When a function is completed/executed, all of its variables
are deleted. However, sometimes we want a local variable
Variables Example: global keyword
<?php
$x = 5;
$y = 10;
function myTest()
{
global $x, $y; // refers to the above variables
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Variables Example
 PHP also stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within
functions and can be used to update global variables
directly.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] +
$GLOBALS['y’]; }
myTest();
PHP Data Types
 Variables can store data of different types.
 PHP supports the following data types:
 String : can be any text inside quotes. You can use single or double
quotes:
 Integer : $x=10;
 Float (also called double): $x=10.01;
 Boolean $x=true;
 Array : $cars = array("Volvo","BMW","Toyota");
 Object: are instances of programmer-defined classes
 NULL: A variable of data type NULL is a variable that has no value
assigned to it. $x=null;
 var_dump() function can be used to identify the data type and value of
a variable

PHP Constants
 A constant is an identifier for a simple value. The value cannot be
changed during the script.
 A valid constant name starts with a letter or underscore (no $ sign
before the constant name).
 Unlike variables, constants are automatically global across the entire
script.
 To create a constant, use the define() function.
 Syntax
 define(name, value, case-insensitive)
<?php
define("GREETING", "Welcome to W3Schools.com!",
true);
echo GREETING;
?>
PHP Operators
 PHP divides the operators in the following groups:
 Arithmetic operators {+, -, *, /, %, **}
 Assignment operators {=, +=, -=, *=, /=, %=}
 Comparison operators {==, ===, !=, <>, !==,
>,< ..}
 Increment/Decrement operators {++, --}
 Logical operators {and, or, xor, &&, ||, !}
 String operators {. (concatenation) .= (concatenation
assignment)}
 Array operators {+, ==, ===, !=, <>,!== }
PHP Echo and Print
 In PHP there are two basic ways to get output: echo and print
 Singly quoted strings are treated literally, whereas doubly
quoted strings replace variables with their values
 ECHO  PRINT
 has no return value  has a return value of 1 so it can
 can take multiple parameters be used in expressions
 can be used with or without  can take one argument
parentheses:  can be used with or without
 Faster than print parentheses: print or print ().
echo "<h2>PHP is Fun!</h2>"; print "<h2>PHP is
echo ("Hello world!<br>“); Fun!</h2>"; print "Hello
echo “Hello", “World“; world!<br>";
echo "<h2>$txt1</h2>"; print "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>"; echo $x + print ("Study PHP at
$y; $txt2<br>“); print $x + $y;
PHP String Functions
 Commonly used functions to manipulate strings are
 strlen(): returns the length of a string
 echo strlen("Hello world!");
 str_word_count(): counts the number of words in a string
 echo str_word_count("Hello world!");
 strrev(): reverses a string
 echo strrev("Hello world!");
 strpos(): searches for a specific text within a string
 echo strpos(" Helloworld!", "world"); // outputs 6
 str_replace(): replaces some characters with some other
characters in a string
 echo str_replace("world", "Dolly", "Hello world!"); //
outputs Hello Dolly!
Conditional Statements
 PHP have the following conditional statements:
 Use if to specify a block of code to be executed,
if a specified condition is true
 Use else to specify a block of code to be
executed, if the same condition is false
 Use else if to specify a new condition to test, if
the first condition is false
 Use switch to specify many alternative blocks of
code to be executed
Conditional Statements Example
<?php <?php $favcolor = "red";
$t = date("H"); switch ($favcolor) {
if ($t < "10") case "red":
echo "Your favorite color is red
{
break;
echo "Have a good
case "blue":
morning!";
echo "Your favorite color is bl
}
break;
elseif ($t < "20") { case "green":
echo "Have a good echo "Your favorite color is
day!"; green!";
} break;
else { default:
echo "Have a good echo "Your favorite color
PHP Loops
 PHP supports different kinds of loops:
 for
 loops through a block of code a number of times
 foreach
 loops through elements of an array
 while
 loops through a block of code while a specified
condition is true
 do/while
 also loops through a block of code while a specified
condition is true
For Loop
 The for loop has the following syntax;
Foreach Loop
 Works only on arrays, and is used to loop through
each key/value pair in an array.
The While Loop
 The while loop loops through a block of code as long
as a specified condition is true.
The do/while loop
 This loop executes the code block at least once, before
checking if the condition is true, then it will repeat
the loop as long as the condition is true.
PHP Arrays
 In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Using array() function
 $cars = array("Volvo", "BMW", "Toyota");
 On the fly
 $cars[0]=“Volvo”; $cars[1]=“BMW”;
 Associative arrays - Arrays with named keys
 Using array() function
 $age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
 On the fly
 $age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] =
"43";
Array Examples
 The count() function is used to return the length of an
array
Some PHP Array Functions
 sort() - sort arrays in ascending order , rsort() - sort
arrays in descending order
 asort() - sort associative arrays in ascending order,
according to the value
 array_keys() - returns all the keys of an array
 array_multisort() - sorts multiple or multi-dimensional
arrays
 array_push() - inserts one or more elements to the
end of an array
 array_reverse() - returns an array in the reverse
order
 array_search() - searches an array for a given value
and returns the key
PHP Functions
 Besides the built-in PHP functions, we can create our own
functions.
 A function will not execute immediately when a page loads.
Instead will be executed by a call to the function
 Syntax
 function functionName(){ code to be executed; }
 Function with parameters
 function functionName($param1, $param2){ code to
be executed; }
 Function with default argument
 function functionName($param1=5, $param2){ code
to be executed; }
 Returning values
Global Variables - Superglobals
 Superglobal variables
 are built-in variables that are always available in all
scopes,
 can be accessed from any function, class or file without
having to do anything special
 Some of the superglobal variables are:
 $GLOBALS : is used to access global variables from
anywhere in the PHP script
 $_SERVER: holds information about headers, paths,
and script locations.
 $_REQUEST: is used to collect data after submitting an
HTML form.

$_SERVER Super global
 $_SERVER holds information about headers, paths, and
script locations.
$_POST Super global
 $_POST is used to collect form data after submitting an HTML
form with method="post”
$_GET Super global
 $_GET used to collect form data after submitting an HTML
form with method="get“
 $_GET can also collect data sent along with a URL
<html>
<body>
<a href=“test_get.php?num1=2&num2=3”> Test
$GET </a>
</body>
</html>
<html>
test_get.ph
<body>
p
<? php echo “Product= “. $_GET[‘num1’]*$_GET[‘num2’];
?>
</body>
PHP Date and Time
 The date() function formats a timestamp to a more
readable date and time.
 Syntax
 date(format,timestamp)
 format Required. Specifies the format of the timestamp
 d - Represents the day of the month (01 to 31)
 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)
 l (lowercase 'L') - Represents the day of the week
 timestamp Optional.
 Specifies a timestamp: which is a sequence of characters,
denoting the date and/or time at which a certain event
occurred.
Date Examples
PHP Include Files
 PHP Include & Require Statements
 are used to insert the content of one PHP file into
another PHP file (before the server executes it)
 Syntax
 include 'filename'; or require 'filename';
 The include and require statements are identical, except
upon failure:
 If a file is not found require will produce a fatal error
and stop the script whereas include will only produce a
warning and the script will continue
 So, if you want the execution to go on and show users
the output, even if the include file is missing, use the
include statement.
include & require Examples
vars. php
PHP Manipulating Files
 PHP has several functions for creating, reading,
uploading, and editing files.
 fopen(filename, openingMode):
 opens a file, on a file that does not exist, it will
create it, given that the file is opened for writing
(w) or appending (a).
 fclose(pointerToOpenedFile):
 is used to close an open file
 feof(pointerToOpenedFile):
 checks if the "end-of-file" (EOF) has been reached
PHP File Opening Modes
 r Read only. File pointer at the start of the file
 r+ Read/Write. File pointer at the start of the file
 w Write only. Overwrites the file
 w+ Read/Write. Overwrites the file
 a Append. File pointer at the end of the file.
 If the file doesn't exist, fopen() will try to create the file
 a+ Read/Append. File pointer at the end of the file.
 x Create and open for write only.
 File pointer at the beginning of the file.
 If the file already exists, the fopen() call will fail and generate an
error. If the file does not exist, try to create it
 x+ Create and open for read/write.
 File pointer at the beginning of the file.
 If the file already exists, the fopen() call will fail and generate an
error.
PHP Read from File Functions
 readfile(filename):
 reads a file and writes it to the output buffer
 fread(param1, param2): reads from an open file
 param1: contains the name of the file to read from
 param2: specifies the maximum number of bytes
to read
 fgets(pointerToOpenedFile)
 is used to read a single line from a file
 fgetc(pointerToOpenedFile)
 is used to read a single character from a file
PHP File
Manipulation
Examples
PHP File
Manipulation
Examples
PHP Write to File Functions
 fwrite(param1, param2) function is used to write to a
file.
 param1: contains the name of the file to write to
and
 param2: is the string to be written
PHP Locking Files
 File locking mechanisms
 With many users accessing your scripts at the same
time, your files could quickly become corrupt.
 flock() function
 locks a file and won’t allow other processes to write
or read the file while the current process is running.
 Syntax :
 flock(pointerToOpenedFile, lockingMode)
 flock($fp1, 1); //shared lock – allows read, doesn’t allow write
 flock($fp2, 2); //exclusive lock – doesn’t allow neither read,
nor write
PHP Locking Example
<?php
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX)){
fwrite($file,"Write something");
// release lock flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file); ?>
PHP File Manipulation Methods
 PHP has a lot of built in functions that you can use
with file processing.
 Some of them are
 “file_exists()”, “is_file()”, “is_dir()”, “is_readable()”,
“is_writeable()”, “is_executable()”;
 functions that return information on files:
 “filesize()”, “fileatime()”, “filemtime()”,
“filectime()”
 copy(), delete(), filetype(), fseek(), ftell(),
mkdir()
Cookes and Sessions
 HTTP is stateless – it does not keep track of the client
between requests
 But sometimes we need to keep track of this
information
 Shopping cart
 “Remember me” on login sites
 2 solutions to this issue
 Cookies – small file stored client-side
 Sessions – relevant data stored on the server
Cookies
 A cookie is a small file that the server stores on the
user's computer for tracking purposes.
 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
Create Cookies with PHP
 A cookie is created with the setcookie() function.
 Syntax
 setcookie(name, value, expire, path, domain,
secure);
 Only the name parameter is required. All other parameters
are optional.
 The setcookie() function must appear BEFORE the
<html> tag.
 The global variable $_COOKIE[] is used to
retrieve value of a cookie
 Syntax
 $_COOKIE[cookieName]
Cookies Example

 The example creates a cookie named "user" with the value "John
Doe". The cookie will expire after 1 day(86400). The "/" means that
the cookie is available in entire website
Setting Cookies
 Cookies are usually set in an HTTP header
HTTP/1.1 200 OK HTTP response
Date: Fri, 04 Feb 2000 21:03:38 GMT
message:
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
From Server to
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07
Browser
22:03:38 GMT; path=/;
domain=tutorialspoint.com
Connection: close
Content-Type: text/html
 If a browser is configured to store cookies, it will
then keep this information until the expiry date.
Sending Cookies Back to Server
 If the user points the browser at any page that
matches the path and domain of the cookie, it will
resend the cookie to the server. The browser's headers
might
GET look something like this:
/ HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac
ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */* HTTP request
Accept-Encoding: gzip message: From
Accept-Language: en Browser to Server
Accept-Charset: iso-8859-1,*,utf-8
Manipulating cookies cont’d
 Modify a Cookie Value
 To modify a cookie, just set (again) the cookie using
the setcookie() function
 Delete a Cookie
 To delete a cookie, use the setcookie() function
with an expiration date in the past
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
 Two main disadvantages of cookies
 Limited in size by browser
 Stored client-side " users / malicious people can
Sessions
 Two main disadvantages of cookies
 Limited in size by browser
 Stored client-side users / malicious people can
change
 Sessions store user data on the server
 Limited only by server space
 Cannot be modified by users
 A potential downside to sessions is that they expire
when
the browser is closed
 Sessions are identified by a session id: often a small
cookie! But the rest of the data is still stored on the
Sessions cont’d
 An alternative way to make data accessible across the
various
pages of an entire website is to use a PHP Session
 A session creates a file in a temporary directory on
the server where registered session variables and
their values are stored.
 This data will be available to all pages on the site
during that visit.
 The location of the temporary file is determined by a
setting in
the php.ini file called session.save_path.
Sessions cont’d
 When a session is started, the following actions take
place:
 PHP first creates a unique identifier for that
particular session which is a random string of 32
hexadecimal numbers such as
3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to
the user's computer to store unique session
identification string.
 A file is automatically created on the server in the
designated temporary directory and bears the name
of the unique identifier prefixed by sess_ ie
Starting a Session
<?php
 session_start() is used // Start the session
session_start();
to create or resume a ?>
session <!DOCTYPE html>
 The session_start() <html>
function must be the <body
<?php
very first thing in your // Set session
document. Before any variables
HTML tags $_SESSION["favcolor"]
 Session variables are set = "green";
$_SESSION["favanimal"] = "cat";
with the PHP global echo "Session variables are
variable set.";
$_SESSION echo $_SESSION["favcolor"];
Destroy a PHP Session
 To remove all <?php
global session_start(); ?>
<!DOCTYPE html>
session <html>
variables and <body>
destroy a <?php
session, use // remove all session
session_unset variables session_unset();
() and // destroy the session
session_destr session_destroy();
oy() ?>
</body>
Cookies vs Sessions
Cookies Sessions
Where is Locally on client Remotely on server
data stored?
Expiration? Variable – Session is destroyed
determined when when the browser is
cookie is set closed
Size limit? Depends on browser Depends only on server
(practically no size
limit)
Accessing $_COOKIE $_SESSION
information?
General use? Remember small Remembering varying
things about the amount of data about
user, such as the user in one
login name. browsing “session”.
PHP Header() Function
 The header() function sends a raw HTTP header to a
client.
 header() must be called before any actual output is
sent to the client
 Syntax
 header(string, replace, http_response_code)
 string Required. Specifies the header string to
send
 replace Optional. Indicates whether the
header should replace previous or add a
second header. Default is TRUE (will replace).
FALSE (allows multiple headers of the same
PHP Header() Function Cont’d
 Prevent page caching:
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00
GMT"); header("Cache-Control: no-cache");
header("Pragma: no-cache"); ?>
<html>
<body>

 Redirect browser to another page
<?php
header("Location: http://www.w3schools.com/"); ?
>
ERROR AND EXCEPTION HANDLING
 The default error handling in PHP is very simple.
An error message with filename, line number
and a message describing the error is sent to
the browser.
 Error handling methods:
 Simple "die()" statements
 Custom errors and error triggers
 Error reporting
Basic Error Handling
 The die() function prints a message and
exits the current script
 Syntax
 die(message)
<?php if(!
file_exists("welcome.txt"))
{
die("File not found");
} else {
$file=fopen("welcome.txt","r"
);
}
EXCEPTION HANDLING
 Proper exception code should include:
 Try - A function using an exception should be in
a "try" block. If the exception does not trigger,
the code will continue as normal. However, if
the exception triggers, an exception is
"thrown"
 Throw - This is how you trigger an
exception. Each "throw" must have at least
one "catch"
 Catch - A "catch" block retrieves an exception
EXCEPTION HANDLING Example
<?php
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
try {
checkNum(2);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Introduction to Object Oriented
PHP
Object Oriented Concepts
 Class: This is a programmer-defined datatype, which
includes local functions as well as local data. You can
think of a class as a template for making many
instances of the same kind (or class) of object.
 Object: An individual instance of the data structure
defined by a class. You define a class once and then
make many objects that belong to it. Objects are also
known as instance.
 Member Variable: These are the variables defined inside
a class. This data will be invisible to the outside of the
class and can be accessed via member functions. These
variables are called attribute of the object once an
object is created.
Object Oriented Concepts Cont’d
 Inheritance: When a class is defined by inheriting
existing function of a parent class then it is called
inheritance. Here child class will inherit all or few
member functions and variables of a parent class.
 Parent class: A class that is inherited from by another
class. This is also called a base class or super class.
 Child Class: A class that inherits from another class.
This is also called a subclass or derived class.
 Polymorphism: This is an object-oriented concept
where the same function can be used for different
purposes. For example, function name will remain
same but it make take different number of arguments
Object Oriented Concepts Cont’d
 Overloading: a type of polymorphism in which some or all
of operators have different implementations depending
on the types of their arguments. Similarly, functions can
also be overloaded with different implementation.
 Data Abstraction: Any representation of data in
which the implementation details are hidden
(abstracted).
 Encapsulation: refers to a concept where we encapsulate
all the data and member functions together to form an
object.
 Constructor: refers to a special type of function which will
be called automatically whenever there is an object
formation from a class.
Defining PHP Classes
 The general form for defining a new class in PHP is
Setter & Getter Methods
 The variable
$this is a
special variable
and it refers to
the same
object, i.e.,
itself.
 -> operator is
equal to java’s
. operator
Creating Objects in PHP
 Once you defined your class, then you can create
as many objects as you like of that class type.
 Creating an object using new operator
Calling Member Functions
 After creating your objects, you will be able to call
member functions related to that object.
PHP Object Constructors
 PHP provides a special function called
construct() to define a constructor/object creator.
PHP Object Destructor
 Like a constructor function you can define a
destructor function using function destruct().
You can release all the resources with-in a
destructor.
Inheritance
 PHP class definitions can optionally inherit from a
parent class definition by using the extends clause.
The syntax is as follows:

 The effect of inheritance is that the child class


automatically inherits:
– All member variables and functions of the
PHP Inheritance Example
 Example
 The following Novel class
inherits Books class and
adds more functionality
based on the requirement.
Function Overriding
 Function definitions in child classes can override
definitions of functions with the same name in
parent classes. In a child class, we can modify the
definition of a function inherited from parent class.
In the Parent In the Child Class
Class
Member Variables
 Public Members
 Unless you specify otherwise, properties and
methods of a class are public. That is to say, they
may be accessed in three possible situations:
 From outside the class in which it is declared
 From within the class in which it is declared
 From within another class that implements the
class in which it is declared
 If you wish to limit the accessibility of the
members of a class then you define class
members as private or protected
Member Variables Cont’d
 Private Member
 By designating a member private, you limit
its accessibility to the class in which it is
declared.
 A private member cannot be referred from
classes that inherit the class and cannot
be accessed from outside the class.
 A class member can be made private by
using private keyword
Private Members Example

 When MyClass class is inherited by another class using


extends, myPublicFunction() will be visible, as will $driver.
The extending class will not have any awareness of or
access to myPrivateFunction and $car, because they are
Member Variables Cont’d
 Protected Members
 A protected property or method is accessible
in the class in which it is declared, as well as
in classes that extend that class.
 Protected members are not available
outside of those two kinds of classes.
 A class member can be made protected by
using protected keyword in front of the
member.
Protected Members Example
Interfaces
 Interfaces are skeletons which are implemented by
developers
 Syntax to create an interface class

 Then, another class can implement the interface,


like this:
Abstract Classes
 An abstract class is one that cannot be instantiated, only
inherited. You declare an abstract class with the keyword
abstract, like this:

 When inheriting from an abstract class, all methods


marked abstract in the parent's class declaration must
be defined by the child
 Note that the function definitions inside an abstract
class must also be preceded by the keyword abstract. It
is not legal to have abstract function definitions inside
Static Keyword
 Declaring class members or methods as static makes
them accessible without needing an instantiation of the
class.
 A member declared as static cannot be accessed with
an instantiated class object (though a static method
can).
Final Keyword
 The final keyword, which prevents child classes from
overriding a method by prefixing the definition with final.
 If the class itself is being defined final then it cannot be
extended.
 Following example results in Fatal error: Cannot override
final method BaseClass::moreTesting()
Calling Parent Constructors
P
P

You might also like