14. PEAR Package - PHP and MySQL Web Development

  • 9,149 views
Uploaded on

Basic concepts about PEAR Package …

Basic concepts about PEAR Package
Telerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2011/10/11/php-school-academy-meeting
The website and all video materials are in Bulgarian.

This lecture discusses the following topics:

What is PEAR?
Mail
Database
Authentication
XML

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
9,149
On Slideshare
0
From Embeds
0
Number of Embeds
3

Actions

Shares
Downloads
50
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. PEAR Package PHP Extension and Application RepositoryNikolay KostovTechnical Trainerhttp://nikolay.itTelerik Software Academyacademy.telerik.com
  • 2. Summary What is PEAR? Mail Database Authentication XML
  • 3. 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
  • 4. Installing PEAR To install PEAR package management system execute C:PHPgo-pear.bat Listing installed packages: C:>pear list INSTALLED PACKAGES, CHANNEL PEAR.PHP.NET: ========================================= PACKAGE VERSION STATE Mail 1.2.0b1 beta Mail_Mime 1.5.2 stable Mail_mimeDecode 1.5.0 stable Net_SMTP 1.3.2 stable Net_Socket 1.0.9 stable PEAR 1.7.2 stable Structures_Graph 1.0.2 stable
  • 5. Installing PEAR package To install a PEAR package you should know its name and version number Example: C:>pear install Mail_Mime downloading Mail_Mime-1.5.2.tgz ... Starting to download Mail_Mime-1.5.2.tgz (22,176 bytes) ........done: 22,176 bytes downloading Mail_mimeDecode-1.5.0.tgz ... Starting to download Mail_mimeDecode- 1.5.0.tgz (9,281 bytes) ...done: 9,281 bytes install ok: channel://pear.php.net/Mail_Mime-1.5.2 install ok: channel://pear.php.net/Mail_mimeDecode-1.5.0
  • 6. 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
  • 7. Mail Package PHP provides the mail function  Uses sendmail program, available in Lunix/Unix systems  Works only with SMTP servers without encrypted authentication PEAR Mailpackage allows sending trough SMTP servers, that require authentication, using IMAP, generates mails in MIME format, etc.
  • 8. 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
  • 9. Sending Mail with PEAR – Examplerequire "Mail.php";$body = "Как върви?";$to = "Пешо <pe6o@parcuca.com>";$headers = array ("Subject" => "Тема", "From"=>"Pesho <pesho@abv.bg>", "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);
  • 10. 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 Mailmime.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
  • 11. Mime Mail – Examplerequire "Mail.php";require "Mailmime.php";$message Generates the body of the = new Mail_mime();$message->setTXTBody format body"); email in MIME ("text Converts and adds headers in$message->setHTMLBody ("<html>…");$message->addAttachment("homemyfie.zip"); MIME format$body = $message->get();$headers = $message->headers ( array (Fromthe same as The sending is => me@domain.com, To =>email normal you@domain.com, Subject => The zip file));$mail=&Mail::factory ("smtp", …);$mail->send (you@domain.com, $headers,$body);
  • 12. 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
  • 13. DSN DSN – Data Source Name  Address of data source, used by MDB2 to connect to it  Looks like URLmysql://user:password@localhost/mydbibase://sysdba:masterey@localhost//var/db.fdbphptype(dbsyntax)://username:password@protocol+hostspec/database?option=value  Can be provided as an array
  • 14. 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
  • 15. Connecting the Database 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()); Second parameter is array with options  Can specify SSL state, result class to be used, debug level, etc
  • 16. 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 providesthe getMessage() method that returns text representation of last execution error
  • 17. 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
  • 18. Sending Query Example $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()); Notice $res->getMessage() and $affected->getMessage()
  • 19. 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
  • 20. 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
  • 21. 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;
  • 22. 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
  • 23. 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
  • 24. Quoting and Escaping The example: $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).); Will produce string like: insert into employees ( Jack, 1, 2008-01-03, 1000)
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. Auth Example (2)// continue from previous slide$authobj = new Auth(DB, $opt, loginfrm);$authobj->start();if ($authobj->checkAuth()) { /* print data, visible only for registered users */} else { echo Please, login;}
  • 31. Example Logout Page// continue from previous slide$authobj = new Auth(DB, $opt, loginfrm);$authobj->start();if ($authobj->checkAuth()) { $authobj->logout(); $authobj->start(); //not necessary}
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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();<?xml version="1.0" encoding="UTF-8"?><palette> <color>red</color> <color>green</color> <color>blue</color></palette>
  • 37. Serializing Associative Array – Example…$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>
  • 38. 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)
  • 39. 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
  • 40. 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
  • 41. Unserializing example<?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);Array ( [color] => Array ( [0] => red [1] => green [2] => blue ))
  • 42. 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>Array ( [red] => 45 [green] => 100 [blue] => 80)
  • 43. PEAR Package1. Install the following PEAR packages:  MDB2, MDB2_Driver_mysql, Mail_Mime, XML_Serializer2. Using PEAR MDB2 implement the following:  Connect to MySQL database  Show all data from MySQL table Messages  Insert new message3. 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.
  • 44. PEAR Package курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  • 45. 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