14. PEAR Package - PHP and MySQL Web Development
-
Upload
telerik-software-academy -
Category
Education
-
view
9.684 -
download
2
description
Transcript of 14. PEAR Package - PHP and MySQL Web Development
PEAR PackagePHP Extension and Application Repository
Nikolay Kostov
Telerik Software Academyacademy.telerik.com
Technical Trainerhttp://nikolay.it
http://academy.telerik.com/.../php-school-academy-meeting
Summary What is PEAR? Mail Database Authentication XML
What is PEAR? PEAR is a set of classes and templates, available in the PHP distribution Provides large set of reusable
components
Object-oriented
Aids and speeds up development
Fixes some cross-platform issues
Installing PEAR To install PEAR package management system execute C:\PHP\go-pear.bat
Listing installed packages:C:\>pear listINSTALLED PACKAGES, CHANNEL PEAR.PHP.NET:=========================================PACKAGE VERSION STATEMail 1.2.0b1 betaMail_Mime 1.5.2 stableMail_mimeDecode 1.5.0 stableNet_SMTP 1.3.2 stableNet_Socket 1.0.9 stablePEAR 1.7.2 stableStructures_Graph 1.0.2 stable
C:\>pear listINSTALLED PACKAGES, CHANNEL PEAR.PHP.NET:=========================================PACKAGE VERSION STATEMail 1.2.0b1 betaMail_Mime 1.5.2 stableMail_mimeDecode 1.5.0 stableNet_SMTP 1.3.2 stableNet_Socket 1.0.9 stablePEAR 1.7.2 stableStructures_Graph 1.0.2 stable
Installing PEAR package
To install a PEAR package you should know its name and version number
Example:C:\>pear install Mail_Mimedownloading Mail_Mime-1.5.2.tgz ...Starting to download Mail_Mime-1.5.2.tgz (22,176 bytes) ........done: 22,176 bytesdownloading Mail_mimeDecode-1.5.0.tgz ...Starting to download Mail_mimeDecode-1.5.0.tgz (9,281 bytes) ...done: 9,281 bytesinstall ok: channel://pear.php.net/Mail_Mime-1.5.2install ok: channel://pear.php.net/Mail_mimeDecode-1.5.0
C:\>pear install Mail_Mimedownloading Mail_Mime-1.5.2.tgz ...Starting to download Mail_Mime-1.5.2.tgz (22,176 bytes) ........done: 22,176 bytesdownloading Mail_mimeDecode-1.5.0.tgz ...Starting to download Mail_mimeDecode-1.5.0.tgz (9,281 bytes) ...done: 9,281 bytesinstall ok: channel://pear.php.net/Mail_Mime-1.5.2install ok: channel://pear.php.net/Mail_mimeDecode-1.5.0
PEAR Public Web Site PEAR Public Web Site contains lots of open-source PEAR packages for free use
http://pear.php.net/packages.php
Contains package name, documentation, tutorials, examples, etc.
PEAR packages are object-oriented Everyone can submit new packages for public use
Mail Package PHP provides the mail function
Uses sendmail program, available in Lunix/Unix systems
Works only with SMTP servers without encrypted authentication
PEAR Mail package allows sending trough SMTP servers, that require authentication, using IMAP, generates mails in MIME format, etc.
Sending Mail Sending email with PEAR is done in 3 steps: Include the PEAR libraries
The Mail.php file is usually enough
Create new instance of the needed mail backend with the factory method Supports "mail", "sendmail", "smtp"
Send the email with the send method
Sending Mail with PEAR – Example
require "Mail.php";$body = "Как върви?";$to = "Пешо <[email protected]>";
$headers = array ("Subject" => "Тема","From"=>"Pesho <[email protected]>","To" => $to,"Content-Type" =>
"text/plain; charset=UTF-8";
$smtpinfo = array ("host"=>"smtp.server.com","port" => "25", "auth" => true,"username" => "smtp_user","password" => "smtp_password");
$mail_obj=&Mail::factory("smtp", $smtpinfo);$mail_obj->send($to, $headers, $body);
require "Mail.php";$body = "Как върви?";$to = "Пешо <[email protected]>";
$headers = array ("Subject" => "Тема","From"=>"Pesho <[email protected]>","To" => $to,"Content-Type" =>
"text/plain; charset=UTF-8";
$smtpinfo = array ("host"=>"smtp.server.com","port" => "25", "auth" => true,"username" => "smtp_user","password" => "smtp_password");
$mail_obj=&Mail::factory("smtp", $smtpinfo);$mail_obj->send($to, $headers, $body);
Mime Mails The PEAR package also provides the Mail_mime class Provides tools for sending emails
with attachments, alternative content and etc.
Located in the Mail\mime.php file in the PEAR directory
The class is used only for generating the content of the mail, sending is handled the same way, as normal email
Mime Mail – Examplerequire "Mail.php";require "Mail\mime.php";
$message = new Mail_mime();$message->setTXTBody ("text body");$message->setHTMLBody ("<html>…");$message->addAttachment("\home\myfie.zip");$body = $message->get();
$headers = $message->headers (array ('From' => '[email protected]','To' => '[email protected]','Subject' => 'The zip file'));
$mail=&Mail::factory ("smtp", …);$mail->send ('[email protected]', $headers, $body);
require "Mail.php";require "Mail\mime.php";
$message = new Mail_mime();$message->setTXTBody ("text body");$message->setHTMLBody ("<html>…");$message->addAttachment("\home\myfie.zip");$body = $message->get();
$headers = $message->headers (array ('From' => '[email protected]','To' => '[email protected]','Subject' => 'The zip file'));
$mail=&Mail::factory ("smtp", …);$mail->send ('[email protected]', $headers, $body);
Generates the body of the email in MIME formatConverts and adds headers in MIME format
The sending is the same as normal email
DB (MDB2) DB is abstract layer for database
handling Newer version of PEAR merged it with
other packages and renamed it to MDB2
Object oriented approach
Emulates replace, sequence, prepare/execute and others if the RDBMS do not support it
Allows secure connection with SSL
Installing: pear install MDB2 MDB2_Driver_mysql
DSN DSN – Data Source Name
Address of data source, used by MDB2 to connect to it
Looks like URL
Can be provided as an array
mysql://user:password@localhost/mydbibase://sysdba:masterey@localhost//var/db.fdbphptype(dbsyntax)://username:password@protocol+hostspec/database?option=value
mysql://user:password@localhost/mydbibase://sysdba:masterey@localhost//var/db.fdbphptype(dbsyntax)://username:password@protocol+hostspec/database?option=value
Connecting the Database
MDB2 provides 3 methods factory() – will instantiate the
driver, but will not connect until required Useful if application may not require
DB connection at all
connect() – will immediately connect
singleton() – checks if connection is already established and returns reference to it Better than creating global DB object
Connecting the Database
Second parameter is array with options Can specify SSL state, result class
to be used, debug level, etc
require_once "MDB2.php";$dsn = array (
'phptype' => 'mysql','username' => 'user','password' => 'mypass','database' => 'mydb');
$options = array ();$mdb = &MDB2::factory ($dsn, $options);if (PEAR::isError($mdb))
die ($mdb->getMessage());
require_once "MDB2.php";$dsn = array (
'phptype' => 'mysql','username' => 'user','password' => 'mypass','database' => 'mydb');
$options = array ();$mdb = &MDB2::factory ($dsn, $options);if (PEAR::isError($mdb))
die ($mdb->getMessage());
The isError() method PEAR and all classes in the package provide the isError() method Static function
Checks if an object is PEAR error object
It is always clearer to call PEAR::isError instead of MDB2::isError for example This is stated by the PEAR
developers
Each package provides the getMessage() method that returns text representation of last execution error
Sending SQL Query There are several methods for querying the database All are methods of created MDB2
connection object (result of factory(), connect() or singleton() methods)
query() is the most direct, used for selecting data Returns a new MDB2 result object or
error object
exec() is used for modification queries Returns number of affected rows or
error
Sending Query Example
Notice $res->getMessage() and $affected->getMessage()
$mdb = &MDB2::factory ($dsn, $options);if (PEAR::isError($mdb))
die ($mdb->getMessage());
$res = &$mdb->query ("select * from foo");if (PEAR::isError($res))
die ($res->getMessage());
$affected = &$mdb->exec("delete from foo");if (PEAR::isError($affected))
die ($affected >getMessage());
$mdb = &MDB2::factory ($dsn, $options);if (PEAR::isError($mdb))
die ($mdb->getMessage());
$res = &$mdb->query ("select * from foo");if (PEAR::isError($res))
die ($res->getMessage());
$affected = &$mdb->exec("delete from foo");if (PEAR::isError($affected))
die ($affected >getMessage());
Select Results The object, returned from query method has several methods for fetching the data fetchOne() – return single field from
a column
fetchRow() – fetch entire row and move to next row
fetchCol(), fetchAll() – returns the data from all rows, respectively single or all columns
Fetch Modes MDB2 provides three modes for the
data, returned by the fetch methods Ordered – default way, arrays returned
are with numeric indexes, same order as in the query
MDB2_FETCHMODE_ORDERED
Associative – indexes of the array are the names of the fields
MDB2_FETCHMODE_ASSOC
Object – returns object, instead of array, the properties names match the fields names
MDB2_FETCHMODE_OBJECT
Fetch Modes The fetch mode can be set with the setFetchMode method of the MDB2 object or can be supplied to the fetchRow method$mdb = &MDB2::factory ($dsn, $options);if (PEAR::isError($mdb))
die ($mdb->getMessage());
//set default fetch mode$mdb->setFetchMode(MDB2_FETCHMODE_OBJECT);$res = &$mdb->query ("select * from foo");
while ($row = &$res->fetchRow())echo $row->id;
$mdb = &MDB2::factory ($dsn, $options);if (PEAR::isError($mdb))
die ($mdb->getMessage());
//set default fetch mode$mdb->setFetchMode(MDB2_FETCHMODE_OBJECT);$res = &$mdb->query ("select * from foo");
while ($row = &$res->fetchRow())echo $row->id;
More MDB2 fetchRow() also can accept second parameter – the row number to fetch
The result object has several useful methods: rowCount(), numCols() getColumnNames() seek() – jump to row in the result
MDB2 provides methods for working with BLOBs as streams
Quoting and Escaping MDB2 provides quote() method
Specific to the database
Formats the data accordingly
Important parameters
Data (some variable or value)
Data type (optional) , e. g. "integer", "text", "timestamp", etc.
The escape methods is similar but does not quote the value
Quoting and Escaping The example:
Will produce string like:
$query = 'insert into employees (name, isWorking, dateHired, salary) values ('. $mdb->quote($name, 'text').', ', $mdb->quote($isWorking, 'boolean').', '. $mdb->quote($dateHired, 'date').', '. $mdb->quote($salary, 'integer').')';
$query = 'insert into employees (name, isWorking, dateHired, salary) values ('. $mdb->quote($name, 'text').', ', $mdb->quote($isWorking, 'boolean').', '. $mdb->quote($dateHired, 'date').', '. $mdb->quote($salary, 'integer').')';
insert into employees ('Jack', 1, '2008-01-03', 1000)
insert into employees ('Jack', 1, '2008-01-03', 1000)
PEAR Authentication PEAR provides several simple class for
authentication purposes Uses database for storing the
username and password information Provides simple methods for checking
valid user, registering, etc. Downsides
Does not provide methods for user access levels
Does not provide automated way to store IP as part of the login data
Also provides classes for HTTP and RADIUS authentication
PEAR Auth Object All the authorization methods are in the Auth class The constructor takes several
parameters Storage driver (usually database,
identified by "DB")
Options array
Name of function that prints login form
Boolean: whether authentication is required
The start() method initializes the authentication process
Auth Options The constructor options are supplied as
associative array dsn – data source name, required table – required when using database usernamecol , passwordcol - the
names of the columns that hold the user names and passwords
cryptType – the function used to encrypt the password (MD5, SHA, etc)
db_fields – comma separated list of fields that should be fetched with the user data
Can use * for all
Auth methods checkAuth – returns boolean, whether valid session authentication information exists
logout – closes the session addUser – adds new user to the database First two parameters are the
username and password, the rest are optional and depend on the database structure
getAuthData() – returns extra information, stored in the Auth session
Auth – Example
$opt = array ( 'dsn' => 'mysql://user:pass@localhost/db', 'db_fields' => '*', 'usernamecol' => 'username', 'passwordcol' => 'pass');
// note the parameters suppliedfunction loginfrm ($username = null, $status=null, &$auth=null) { echo "<form method=\"post\"… // it is required to send over post, // fields are named "username" and "password"}
// continue to next slide
$opt = array ( 'dsn' => 'mysql://user:pass@localhost/db', 'db_fields' => '*', 'usernamecol' => 'username', 'passwordcol' => 'pass');
// note the parameters suppliedfunction loginfrm ($username = null, $status=null, &$auth=null) { echo "<form method=\"post\"… // it is required to send over post, // fields are named "username" and "password"}
// continue to next slide
Auth Example (2)
// continue from previous slide$authobj = new Auth('DB', $opt, 'loginfrm');
$authobj->start();if ($authobj->checkAuth()) {
/* print data, visible only forregistered users */
} else {echo 'Please, login';
}
// continue from previous slide$authobj = new Auth('DB', $opt, 'loginfrm');
$authobj->start();if ($authobj->checkAuth()) {
/* print data, visible only forregistered users */
} else {echo 'Please, login';
}
Example Logout Page
// continue from previous slide$authobj = new Auth('DB', $opt, 'loginfrm');
$authobj->start();if ($authobj->checkAuth()) {
$authobj->logout();$authobj->start(); //not necessary
}
// continue from previous slide$authobj = new Auth('DB', $opt, 'loginfrm');
$authobj->start();if ($authobj->checkAuth()) {
$authobj->logout();$authobj->start(); //not necessary
}
XML PEAR provides packages for both parsing and serializing of XML data Supports Unicode XML files
PHP has great support of reflection objects Objects that create properties at
runtime
This gives tools to easily turn XML into objects and vice-versa
XML_Serializer The PEAR XML_Serializer class is used to turn objects and arrays into XML Main methods:
serialize ($data) – turns PHP data structure into XML, returns true or PEAR Error object
getSerializedData – returns the serialized XML document
setOptions – sets serializing options
Same options can be passed to the class constructor
XML_Serializer options addDecl – boolean, whether to add XML declaration "<?xml version… ?>"
encoding – sets document encoding Added to the XML declaration too
defaultTagName – tag name used to serialize the values in indexed array
rootName – the name of the root tag rootAttributes – associative array with attributes to add to the root tag
XML_Serializer options scalarAsAttributes – boolean, for
associative arrays. If values in array are scalars they will be added as attributes of the tag
addDoctype – boolean, if doctype declaration should be added to the document
doctype – specify the URIs to be user in the DOCTYPE declaration
typeHints –sets if type/class info should be stored too
Serializing – Examplerequire_once 'XML/Serializer.php';$palette = array ('red', 'green', 'blue');$options = array (
"addDecl" => true,"encoding" => 'UTF-8',"rootName"=> 'palette',"defaultTagName" => 'color');
$serializer = new XML_Serializer($options);$serializer->serialize($palette);$xml = $serializer->getSerializedData();
require_once 'XML/Serializer.php';$palette = array ('red', 'green', 'blue');$options = array (
"addDecl" => true,"encoding" => 'UTF-8',"rootName"=> 'palette',"defaultTagName" => 'color');
$serializer = new XML_Serializer($options);$serializer->serialize($palette);$xml = $serializer->getSerializedData();
<?xml version="1.0" encoding="UTF-8"?><palette>
<color>red</color><color>green</color><color>blue</color>
</palette>
<?xml version="1.0" encoding="UTF-8"?><palette>
<color>red</color><color>green</color><color>blue</color>
</palette>
Serializing Associative Array – Example
…$data = array ( 'red' => 45, 'green' => 100,
'blue' => 80);…$serializer->serialize($data);…
…$data = array ( 'red' => 45, 'green' => 100,
'blue' => 80);…$serializer->serialize($data);…
<?xml version="1.0" encoding="UTF-8"?><palette>
<red>45</red><green>100</green><blue>80<blue>
</palette>
<?xml version="1.0" encoding="UTF-8"?><palette>
<red>45</red><green>100</green><blue>80<blue>
</palette>
XML_Unserialize PEAR XML_Unserialize class parses XML data and returns nested associative and indexed arrays Allows parsing to create objects
instead of arrays If the necessary classes are defined
and there is class information in the XML
Unlike unserialize function does not have magic method to call (__wakeup)
XML_Unserialize Like the serializer class has one main method unserialize ($data, $isFile, $options)
If $isFile is supplied as true, the class considers $data to be file name or stream resource to read the XML from
options can be supplied to the constructor, the unserialize method or via the setOptions method
XML_Unserialize options
parseAttributes
If set to true tag attributes are parsed into arrays
attributesArray
The name of the array into which attributes data will be placed
tagMap
Allows mapping of XML tag to a PHP class to parse the data into
Unserializing example
<?xml version="1.0" encoding="UTF-8"?><palette>
<color>red</color><color>green</color><color>blue</color>
</palette>
<?xml version="1.0" encoding="UTF-8"?><palette>
<color>red</color><color>green</color><color>blue</color>
</palette>
$unserializer = new XML_Unserializer();$unserializer->unserialize($xml);$unserializer = new XML_Unserializer();$unserializer->unserialize($xml);
Array ([color] => Array (
[0] => red[1] => green[2] => blue
))
Array ([color] => Array (
[0] => red[1] => green[2] => blue
))
Unserializing example Using the same code
This time we get back the same data<?xml version="1.0" encoding="UTF-8"?>
<palette><red>45</red><green>100</green><blue>80<blue>
</palette>
<?xml version="1.0" encoding="UTF-8"?><palette>
<red>45</red><green>100</green><blue>80<blue>
</palette>
Array ([red] => 45[green] => 100[blue] => 80
)
Array ([red] => 45[green] => 100[blue] => 80
)
PEAR Package1. Install the following PEAR packages:
MDB2, MDB2_Driver_mysql, Mail_Mime, XML_Serializer
2. Using PEAR MDB2 implement the following:
Connect to MySQL database
Show all data from MySQL table Messages
Insert new message
3. Using XML_Serializer convert all messages from the database table Messages to XML file named messages.xml.
4. Send the file messages.xml to your email as attachment.
форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно
програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
курсове и уроци по програмиране, книги – безплатно от Наков
безплатен курс "Качествен програмен код"
алго академия – състезателно програмиране, състезания
ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия
курс мобилни приложения с iPhone, Android, WP7, PhoneGap
free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно
?
? ? ??
?? ?
?
?
?
??
?
?
? ?
Questions?
?
PEAR Package
http://academy.telerik.com
Free Trainings @ Telerik Academy
“PHP & MySQL Web Design" course
academy.telerik.com/.../php-school-academy-meeting
Telerik Software Academy academy.telerik.com
Telerik Academy @ Facebook facebook.com/TelerikAcademy
Telerik Software Academy Forums forums.academy.telerik.com