You are on page 1of 55

Server-side scripting:PHP 1

Unit -3 / 4
PHP Include Files 2

The include (or require) statement takes all the text/code/markup


that exists in the specified file and copies it into the file that uses the
include statement.
It is possible to insert the content of one PHP file into another PHP file
(before the server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the
script
include will only produce a warning (E_WARNING) and the script will
continue
PHP File Handling 3

PHP has several functions for creating, reading,


uploading, and editing files.
readfile() Function 4

The readfile() function reads a file and


writes it to the output buffer.

<?php
echo readfile(“phpmanual.txt");
?>
Open File - fopen() 5

A better method to open files is with the fopen() function. This


function gives you more options than the readfile() function.
The fopen() function is also used to create a file. Maybe a little
confusing, but in PHP, a file is created using the same function
used to open files.
If you use fopen() on a file that does not exist, it will create it,
given that the file is opened for writing (w) or appending (a).
The first parameter of fopen() contains the name of the file to
be opened and the second parameter specifies in which mode
the file should be opened.
Modes 6

r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist.
File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist.
File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
Read File - fread() 7

The fread() function reads from an open file.


The first parameter of fread() contains the name
of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.
txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
Close File - fclose() 8

The fclose() function is used to close an open file.


It's a good programming practice to close all files
after you have finished with them. You don't want an
open file running around on your server taking up
resources!
The fclose() requires the name of the file (or a
variable that holds the filename) we want to close.
File handling functions 9

fgets() :The fgets() function is used to read a


single line from a file.
fgetc(): The fgetc() function is used to read a
single character from a file.
Check End-Of-File - feof() 10

The feof() function checks if the "end-of-file"


(EOF) has been reached.
The feof() function is useful for looping
through data of unknown length.
fwrite()Variables 11

The fwrite() function is used to write to a


file.
The first parameter of fwrite() contains the
name of the file to write to and the second
parameter is the string to be written.
File Upload 12

Some rules to follow for the HTML form above:


Make sure that the form uses method="post"
The form also needs the following attribute: enctype="
multipart/form-data". It specifies which content-type
to use when submitting the form
Without the requirements above, the file upload will not
work.
Stateless nature of HTTP 13
Stateless means there is no record of previous interactions
and each interaction request has be handled based entirely
on information that comes with it.
The HTTP , an application layer above TCP/ IP is also
stateless. Each request from a user for a web page or URL
results in the requested pages being remembering the
request later.
Hidden field (<input type="hidden" name=“Fieldname" >)
Cookies
Sessions
PHP Cookies 14
A cookie is often used to identify a user. A cookie is a small file
that the server embeds on the user's computer. Each time the
same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie
values.

A cookie is created with the setcookie() function.


Syntax :
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are


optional.
Cookie Operations 15

Create/Retrieve a Cookie
Modify a Cookie value
Delete a Cookie
PHP Sessions 16

On the internet there is one problem: 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.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
When a session is started following things
17
happen?

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 sess_3c7foj34c3jj973hjkop2fc937e3443.
PHP Session 18

A PHP session is easily started by making a call to


the session_start() function. This function first checks if a session is
already started and if none is started then it starts one. It is
recommended to put the call to session_start() at the beginning of the
page.
Session variables are stored in associative array called $_SESSION[].
These variables can be accessed during lifetime of a session.
Make use of isset() function to check if session variable is already
set or not.
Session Operations 19

Start Session
Retrieve Session Variable Values
Modify Session variable values
Destroy Session: A PHP session can be destroyed
by session_destroy() function. This function does not need
any argument and a single call can destroy all the session
variables. If you want to destroy a single session variable
then you can use unset() function to unset a session variable.
Query Parameters 20

Query parameters are a defined set of parameters attached


to the end of a url. They are extensions of the URL that
are used to help define specific content or actions based on
the data being passed.

<?php echo "The query string is: ".$_SERVER['QUERY_STRING']; ?>


If the above php code is saved with a filename of QUERY_STRING.php and
if you add '?tutorial=php&section=super-globals' (i.e. QUERY_STRING.php?
tutorial=php&section=super-globals); it will print this string in the page
since you have asked the script to print $SERVER['QUERY_STRING'].
What is a Database? 21

A database is a separate application that stores a


collection of data.
Each database has one or more distinct APIs for
creating, accessing, managing, searching and
replicating the data it holds.
It comes in two flavors:
A flat database
A relational database
Relational databases 22

A Relational DataBase Management System (RDBMS) is a


software that −
Enables you to implement a database with tables, columns
and indexes.
Guarantees the Referential Integrity between rows of
various tables.
Updates the indexes automatically.
Interprets an SQL query and combines information from
various tables.
MySQL Database 23

MySQL is the most popular Open Source


Relational SQL Database Management System.
MySQL is developed, marketed and
supported by MySQL AB, which is a Swedish
company.
It works in perfect harmony with PHP, Perl,
Python and other languages.
Benefits of MySql 24

MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right.
It handles a large subset of the functionality of the most expensive and powerful
database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments
Using MySQL with PHP 25
Php’s strongest feature is its capability
interface with a database. Connecting to the
internet has never been easy.

PHP supports many of the most popular


database servers in the market including PHP.
PHP mysqli_connect function 26

The PHP mysql connect function is used to


connect to a MySQL database server.

It has the following syntax.


<?php; $db_handle =
mysqli_connect($db_server_name, $db_user_name,
$db_password); ?>
PHP mysqli_select_db function 27

The mysqli_select_db function is used to select a


database.

It has the following syntax.


<?php mysqli_select_db($db_handle,$database_name); ?>
PHP mysqli_query function 28

The mysqli_query function is used to execute SQL


queries.
The function can be used to execute the following
query types: Insert, Select, Update, delete
It has the following syntax.
<?php mysqli_query($db_handle,$query) ; ?>
PHP mysqli_num_rows function 29

The mysqli_num_rows function is used to get the


number of rows returned from a select query.

It has the following syntax.


<?php mysqli_num_rows($result); ?>
PHP mysqli_fetch_array function 30

The mysqli_fetch_array function is used fetch


row arrays from a query result set.

It has the following syntax.


<?php mysqli_fetch_array($result); ?>
PHP mysqli_close function 31

The mysqli_close function is used to close an


open database connection.

It has the following syntax.


<?php mysqli_close($db_handle); ?>
Exception & Exception Handling 32

What is an Exception?
An exception is an unexcepted outcome of a program, which can be
handled by the program itself. Basically, an exception disrupts the
normal flow of the program. But it is different from an error because an
exception can be handled, whereas an error cannot be handled by the
program itself.

Exception handling is a powerful mechanism of PHP, which is used to


handle runtime errors (runtime errors are called exceptions). So that
the normal flow of the application can be maintained.
The main purpose of using exception handling is to maintain the
normal execution of the application.
Exception Handling 33
PHP offers the following keywords for this purpose:
try -
The try block contains the code that may have an exception or where an exception can arise.
When an exception occurs inside the try block during runtime of code, it is caught and
resolved in catch block. The try block must be followed by catch or finally block. A try block
can be followed by minimum one and maximum any number of catch blocks.
catch -
The catch block contains the code that executes when a specified exception is thrown. It is
always used with a try block, not alone. When an exception occurs, PHP finds the matching
catch block.
throw -
It is a keyword used to throw an exception. It also helps to list all the exceptions that a
function throws but does not handle itself.
Remember that each throw must have at least one "catch".
finally -
The finally block contains a code, which is used for clean-up activity in PHP. Basically, it
executes the essential code of the program.
Exception Handling 34

What happens when an exception is triggered -


•The current state of code is saved.
•The execution of the code is switched to a predefined
exception handler function.
•Depending on the situation, the handler can halt the
execution of program, resume the execution from the saved
code state, or continue the execution of the code from
another location in the code.
Advantage of Exception Handling 35

Exception handling is an important mechanism in PHP, which have


the following advantages over error handling -
Grouping of error types -
In PHP, both basic and objects can be thrown as exception. It can
create a hierarchy of exception objects and group exceptions in
classes and also classify them according to their types.
Keep error handling and normal code separate -
In traditional error handling, if-else block is used to handle errors. It
makes the code unreadable because the code for handling errors
and conditions got mixed. Within the try-catch block, exception
keeps separate from the code and code become readable.
PHP try-catch 36
<?php
//try block
try {
//code that can throw exception
}
//catch block
catch (Exception $e) {
//code to print exception caught in the block
}
//finally block
finally {
//any code that will always execute
}
?> Example
Security – Authentication (user logins) 37

Authentication
There are two parts to the authentication process:
The login form. The user is presented with some way of entering their
credentials; the system checks these against a list of known users; if a
match is found, the user is authenticated. This part of the system
generally also initiates some way of remembering that a user is
authenticated (such as by setting a cookie) so that this process doesn't
have to be repeated for each request.
The per-request check (for want of a better name!). This is the same as the
second part of the login form process, with the user credentials being
acquired from a source more convenient to the user—such as the cookie.
Security- Authorization (Permissions) 38

Authorization is what permissions do they have in the


system. Can they create a user, send an email, access
sensitive data?
What is SQL Injection? 39
SQL Injection (SQLi) is a type of an injection attack that makes it possible to execute
malicious SQL statements. These statements control a database server behind a web
application.
Attackers can use SQL Injection vulnerabilities to bypass application security measures.
They can go around authentication and authorization of a web page or web application
and retrieve the content of the entire SQL database.
They can also use SQL Injection to add, modify, and delete records in the database.
An SQL Injection vulnerability may affect any website or web application that uses an SQL
database such as MySQL, Oracle, SQL Server, or others.

Criminals may use it to gain unauthorized access to your sensitive data: customer
information, personal data, trade secrets, intellectual property, and more. SQL Injection
attacks are one of the oldest, most prevalent, and most dangerous web application
vulnerabilities.
Example of SQL Injection 40

Example
How to Prevent an SQL Injection? 41

The only sure way to prevent SQL Injection attacks is input


validation and parametrized queries including prepared statements.
The application code should never use the input directly. The
developer must sanitize all input, not only web form inputs such as
login forms.
They must remove potential malicious code elements such as single
quotes. It is also a good idea to turn off the visibility of database
errors on your production sites.
The best way to prevent SQL Injections is to use safe programming
functions that make SQL Injections impossible: parameterized
queries (prepared statements) and stored procedures.
Handling special characters in input 42

PHP htmlspecialchars() Function


OOP Programming with PHP 43

OOP stands for Object-Oriented Programming.


Object-oriented programming has several advantages over
procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the PHP code DRY "Don't Repeat Yourself"
, and makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications
with less code and shorter development time
OOP Programming with PHP 44

OOP stands for Object-Oriented Programming.


Object-oriented programming has several advantages over
procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the PHP code DRY "Don't Repeat Yourself"
, and makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications
with less code and shorter development time
PHP - What are Classes and Objects? 45

A class is a template for objects, and an object is


an instance of a class.

When the individual objects are created, they


inherit all the properties and behaviours from the
class, but each object will have different values
for the properties.
Define a Class 46

A class is defined by using the class keyword, followed by


the name of the class and a pair of curly braces ({})
Syntax:
<?php
class Fruit {
// code goes here...
}
?>
Define Objects 47

Classes are nothing without objects! We can create


multiple objects from a class. Each object has all
the properties and methods defined in the class, but
they will have different property values.

Objects of a class is created using the new keyword.


e.g. $apple = new Fruit();
Common OOP Terminologies 48

$this Keyword: The $this keyword refers to the current


object, and is only available inside methods.

instanceof: the instanceof keyword to check if an object


belongs to a specific class
<?php
$apple = new Fruit();
var_dump($apple instanceof(Fruit));
?>
OOP - Constructor 49

A constructor allows you to initialize an object's


properties upon creation of the object.

If you create a __construct() function, PHP will


automatically call this function when you create an object
from a class.

Notice that the construct function starts with two


underscores (__)!
OOP - Destructor 50

A destructor is called when the object is


destructed or the script is stopped or exited.

If you create a __destruct() function, PHP will


automatically call this function at the end of the
script.
OOP - Access Modifiers 51

Properties and methods can have access modifiers which


control where they can be accessed.
There are three access modifiers:
public - the property or method can be accessed from
everywhere. This is default
protected - the property or method can be accessed within
the class and by classes derived from that class
private - the property or method can ONLY be accessed
within the class
PHP - What is Inheritance? 52

Inheritance in OOP = When a class derives from another


class.

The child class will inherit all the public and protected
properties and methods from the parent class. In addition, it
can have its own properties and methods.

An inherited class is defined by using the extends keyword.


PHP - The final Keyword 53
The final keyword can be used to prevent class inheritance or to
prevent method overriding.

<?php
final class Fruit {
// some code
}
// will result in error
class Strawberry extends Fruit {
// some code
}
?>
PHP – Error Handling 54

When creating scripts & web applications, error handling is an


important part. If your code lacks error checking code, your program
may look very unprofessional and you may be open to security risks.
1. Simple die() statement
if(!file.exists(“xyz.txt”))
{
die(“File not found”);
}
else
{
$file = fopen(“xyz.txt”);
}
PHP – Error Handling 55

2. Custom errors & error triggers


Create special function here
Trigger_error(“msg”,constant): generates a user-
level error message.(where constant are
E_WARNING, E_NOTICE, E_USER_ERROR,
E_USER_WARNING,E_USER_NOTICE)
3. Error Reporting

You might also like