howtos » 2007 » April

mysqldump is a useful utility for dumping the contents of an entire database to an SQL file.

CODE:
  1. mysqldump --user=dbusername --password=dbpassword db_name_here> db_name_here.sql

By default the --opt option is enabled, which is a shorthand option for specifying the below options. According to the documentation, using this option "... should give you a fast dump operation and produce a dump file that can be reloaded into a MySQL server quickly".

CODE:
  1. --add-drop-table
  2. --add-locks
  3. --create-options
  4. --disable-keys
  5. --extended-insert
  6. --lock-tables
  7. --quick
  8. --set-charset

cURL is used to interact with remote URLs without needing a user to initiate the process (e.g. by clicking on a form submit button). cURL is useful for submitting HTTP POST/PUT/DELETE requests when dealing with web services. PHP has inbuilt cURL support since PHP 4.0.2 using cURL's libcurl library. Find out more about PHP/CURL -- using libcurl with PHP here.

A fullset of cURL options and what they mean can be found in
PHP's manual entry for curl_setopt().

PHP:
  1. //Contains encoded string to pass along for basic authentication purposes
  2. $auth_token = base64_encode($username . '-' . $password);
  3.  
  4. //Target URL - the URL you want to submit a form to
  5. $target_url = 'http://www.remotesite.com/post_target.php';
  6.  
  7. //Create  a new cURL handle
  8. //Passing the target URL to curl_init allows you to bypass the call curl_setopt($ch, CURLOPT_URL, $target_url);
  9. $ch = curl_init($target_url);
  10.  
  11. //Tell the handler that the info is to be sent using an HTTP POST request
  12. curl_setopt($ch, CURLOPT_POST, true);
  13.  
  14. //Set other relevant headers.  Place each header as an array element
  15. //An alternative to building the Authorization header is to use curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
  16. $headers = array('Authorization: Basic ' . $auth_token,
  17.                  'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3');
  18. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  19.  
  20. //Pass the POST fields - be sure to urlencode your value strings (hint: http_build_query() will do this for you; PHP5)
  21. //Below we assume values have already been posted to this script and kept in $_POST.  We have validated the submission and
  22. // are now posting the same values to a remote URL
  23. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
  24.  
  25. //When we execute the handle, we want curl_exec() to return to a string rather than directly outputting it
  26. curl_setopt($ch, CURLOPT_RETURNTRANSER, true);
  27.  
  28. //Don't use a cached connection - explicitly create a new one
  29. curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
  30.  
  31. //Fail if cannot connect to the target server within 5 seconds
  32. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  33.  
  34. //If the target server returns a redirect request using the "Location:" header directive, then follow it.
  35. //To prevent recursive redirects, only do a max of 5 follows
  36. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  37. curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  38.  
  39. //Let's now execute the handler
  40. //Because CURLOPT_RETURNTRANSFER is true, we need to capture the return value of curl_exec()
  41. $response_data = curl_exec($ch);
  42.  
  43. //Was there an error?
  44. //curl_errno() returns the error code
  45. //curl_error() returns a clear text message for the last cURL operation
  46. if (curl_errno($ch)> 0){
  47.     die('There was a cURL error: ' . curl_error($ch));
  48. } else {
  49.     //Close the handler and release resources
  50.     curl_close($ch);
  51. }
  52.  
  53.  
  54. //Now do something with your data
  55. return myProcessingFunction($data);

CODE:
  1. #Activate the rewrite engine if it isn't so already
  2. RewriteEngine on
  3. #intercept all HTTP requests to the site that do not have a 'www.' at the beginning of the Domain name
  4. #and then force a redirect to the same page address only this time, including the 'www.'
  5. RewriteCond %{HTTP_HOST} !^www\..* [NC]
  6. RewriteRule ^(.*) http://www.%{HTTP_HOST}/$1 [R=301]
  7. #The inverse of the above rule - intercept HTTP requests with a 'www.' at the start and redirect to the non-www version
  8. # Ensure that your serverName directive is set up to the non-www name of your domain
  9. RewriteCond %{HTTP_HOST} ^www\..* [NC]
  10. RewriteRule ^(.*) http://%{SERVER_NAME}/$1 [R=301]

Sending a plain-text e-mail through PHP is a simple process

PHP:
  1. mail ($to, $subject, $message, $headers);

The $to parameter can look like:

example@mysite.com
example@mysite.com, user@mysite.com
Example Sr <example@mysite.com>, Example Jr <user@mysite.com>

Common headers to use in your messages:

PHP:
  1. $headers =  "From: yourname@yoursite.com\r\n
  2.              Reply-To: replyhere@yoursite.com\r\n
  3.              Cc: watcher@yoursite.com\r\n
  4.              Bcc: spy@yoursite.com\r\n
  5.              X-Mailer: YourApplicationNameHere\r\n"

htpasswd is a command line tool for creating and updating user authentication files. These files are primarily used by apache to authenticate HTTP users.

Creating a password file

CODE:
  1. htpasswd -c /path/to/.htpasswd username

Adding a user & password

CODE:
  1. htpasswd -b /path/to/.htpasswd username password

PHP 5's DOM Functions (or extension) allows you to create and manipulate XML documents. In fact, it can also be used to create and manipulate any documents adhering to the DOM3 specifications such as HTML and XHTML documents.

Creation of a DOM document is a fairly simple affair

  • Instantiate DOMDocument - also specify which version of XML the document is in and how it is encoded
  • Create elements through the DOMDocument object
  • Set your elements' properties (e.g. values, attributes, child nodes)
  • Append the elements to your parent DOMDocument
  • Output as fully-formed XML using DOMDocument::saveXML()

The following example shows you how to create an XML document (using UTF-8 encoding) using PHP 5's DOM functions.

PHP:
  1. //First create an XML document
  2. //The following statement sets XML version 1.0, encoding utf-8
  3. $dom = new DOMDocument('1.0', 'utf-8');
  4.  
  5. //Step 1: create the root node
  6. //Now create the root node and declare the XML namespace
  7. $entry_node = $dom->createElementNS('http://www.w3.org/2005/Atom', 'entry');
  8. //If you need to add additional namespace declarations, do it now
  9. $entry_node->setAttribute('xmlns:gd','http://schemas.google.com/g/2005');
  10.  
  11. //Step 2: create all child nodes
  12. $category_node = $dom->createElement('category');
  13. $category_node->setAttribute('scheme', 'http://schemas.google.com/g/2005#kind');
  14. $category_node->setAttribute('term', 'http://schemas.google.com/g/2005#event');
  15.  
  16. $title_node = $dom->createElement('title', $title);
  17. $title_node->setAttribute('type', 'text');
  18.  
  19. $content_node = $dom->createElement('content', $content);
  20. $content_node->setAttribute('type', 'text');
  21.  
  22. //In some cases the child node may itself be a parent with its own child nodes
  23. //Create the parent node
  24. $author_node = $dom->createElement('author');
  25.  
  26. //Create the child nodes
  27. $author_name_node   = $dom->createElement('name', $author_name);
  28. $author_email_node  = $dom->createElement('email', $author_email);
  29.  
  30. //Add the child nodes to the parent
  31. $author_node->appendChild($author_name_node);
  32. $author_node->appendChild($author_email_node);
  33.  
  34. $transparency_node = $dom->createElement('gd:transparency');
  35. $transparency_node->setAttribute('value', 'http://schemas.google.com/g/2005#event.opaque');
  36.  
  37. $eventstatus_node = $dom->createElement('gd:eventStatus');
  38. $eventstatus_node->setAttribute('value', 'http://schemas.google.com/g/2005#event.confirmed');
  39.  
  40. $where_node = $dom->createElement('gd:where');
  41. $where_node->setAttribute('valueString', $where);
  42.  
  43. $when_node = $dom->createElement('gd:when');
  44. $when_node->setAttribute('startTime', $startTime . '+10:00');
  45. $when_node->setAttribute('endTime', $endTime . '+10:00');
  46.  
  47. //Another child node which is also a parent
  48. $reminder_node = $dom->createElement('gd:reminder');
  49. $reminder_node->setAttribute('minutes', $minutes);
  50.  
  51. $when_node->appendChild($reminder_node);
  52.  
  53. //Step 3: Add child nodes to the parent node
  54. $entry_node->appendChild($category_node);
  55. $entry_node->appendChild($title_node);
  56. $entry_node->appendChild($content_node);
  57. $entry_node->appendChild($author_node);
  58. $entry_node->appendChild($transparency_node);
  59. $entry_node->appendChild($eventstatus_node);
  60. $entry_node->appendChild($where_node);
  61. $entry_node->appendChild($when_node);
  62.  
  63.  
  64. //Append the root node to the document
  65. $dom->appendChild($entry_node);
  66.  
  67. //Return the fully-formed XML representation of the DOMDocument
  68. return $dom->saveXML();

Here's how to include another template file within a template file:

PHP:
  1. {include file='includes/menu_calendar.inc.tpl'}

If you have successfully obtained a calendar feed, you should receive some XML looking like this

XML:
  1. <default:feed>
  2.     <default:id>http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/public/basic</default:id>
  3.     <default:updated>2007-04-08T03:38:29.000Z</default:updated>
  4.     <default:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"/>
  5.     <default:title type="text">Vinoaj Vijeyakumaar</default:title>
  6.     <default:subtitle type="text">Vinoaj Vijeyakumaar</default:subtitle>
  7.     <default:link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/public/basic"/>
  8.     <default:link rel="self" type="application/atom+xml" href="http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/public/basic?max-results=25"/>
  9.     <default:author>
  10.         <default:name>Vinoaj Vijeyakumaar</default:name>
  11.         <default:email>vinoajtest@gmail.com</default:email>
  12.     </default:author>
  13.     <default:generator version="1.0" uri="http://www.google.com/calendar">Google Calendar</default:generator>
  14.     <openSearch:totalResults>1</openSearch:totalResults>
  15.     <openSearch:startIndex>1</openSearch:startIndex>
  16.     <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
  17.     <gCal:timezone value="Australia/Sydney"/>
  18.     <default:entry>
  19.         <default:id>
  20.         http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/public/basic/12ps2qhasoejgtf8uo89des4f0
  21.         </default:id>
  22.         <default:published>2007-04-08T03:35:52.000Z</default:published>
  23.         <default:updated>2007-04-08T03:36:23.000Z</default:updated>
  24.         <default:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"/>
  25.         <default:summary type="html">When: Mon Apr 9, 2007<br></default:summary>
  26.         <default:link rel="alternate" type="text/html" href="http://www.google.com/calendar/event?eid=MTJwczJxaGFzb2VqZ3RmOHVvODlkZXM0ZjAgdmlub2FqdGVzdEBt" title="alternate"/>
  27.         <default:link rel="self" type="application/atom+xml" href="http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/public/basic/12ps2qhasoejgtf8uo89des4f0"/>
  28.     </default:entry>
  29. </default:feed>

A fully-formed private event looks something like this

XML:
  1. <entry>
  2.     <id>http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/private/full/12ps2qhasoejgtf8uo89des4f0</id>
  3.     <published>2007-04-08T03:35:52.000Z</published>
  4.     <updated>2007-04-08T03:36:23.000Z</updated>
  5.     <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event"/>
  6.     <title type="text">Easter Monday</title>
  7.     <content type="text"/>
  8.     <link rel="alternate" type="text/html" href="http://www.google.com/calendar/event?eid=MTJwczJxaGFzb2VqZ3RmOHVvODlkZXM0ZjAgdmlub2FqdGVzdEBt" title="alternate"/>
  9.     <link rel="self" type="application/atom+xml" href="http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/private/full/12ps2qhasoejgtf8uo89des4f0"/>
  10.     <author>
  11.         <name>Vinoaj Vijeyakumaar</name>
  12.         <email>vinoajtest@gmail.com</email>
  13.     </author>
  14.     <gd:visibility value="http://schemas.google.com/g/2005#event.public"/>
  15.     <gCal:sendEventNotifications value="false"/>
  16.     <gd:transparency value="http://schemas.google.com/g/2005#event.transparent"/>
  17.     <gd:comments>
  18.         <gd:feedLink href="http://www.google.com/calendar/feeds/vinoajtest%40gmail.com/private/full/12ps2qhasoejgtf8uo89des4f0/comments"/>
  19.     </gd:comments>
  20.     <gd:eventStatus value="http://schemas.google.com/g/2005#event.confirmed"/>
  21.     <gd:where/>
  22.     <gd:when startTime="2007-04-09" endTime="2007-04-10">
  23.         <gd:reminder minutes="10"/>
  24.     </gd:when>
  25. </entry>


The following steps show you how to grab a feed using Zend Framework's GData package and then grab the appropriate values.

PHP:
  1. //Initiate an authorised http client
  2. //See previous post on how to get an auth token and convert it to a session token
  3. $client = Zend_Gdata_AuthSub::getHttpClient($authToken);
  4.  
  5. //Instantiate a new GData Calendar instance + set the identifiers and parameters
  6. $gdata_cal = new Zend_Gdata_Calendar($client);
  7. $gdata_cal->setUser('vinoajtest@gmail.com');
  8. $gdata_cal->setVisibility('private');
  9. $gdata_cal->setProjection('full');
  10.  
  11. //Returns an atom feed object represented by Zend_Feed_Atom
  12. //The Zend_Feed_Atom object is an extension of DOMDocument
  13. //Call Zend_Feed_Atom::saveXML() to acquire a fully-formed DOMDocument at any time
  14. $gdata_cal_feed = $gdata_cal->getCalendarFeed();
  15.  
  16. //Let's spit out some basic FEED information
  17. $n_entries  = $gdata_cal_feed->count()//int
  18. $feed_title = $gdata_cal_feed->title()//str
  19. $feed_id    = $gdata_cal_feed->id();   //str url
  20.  
  21. $feed_links = $gdata_cal_feed->link()//array links
  22. foreach ($feed_links as $ix => $link){
  23.     //Each item is of type DOMElement
  24.     $link_rel  = $link->getAttribute('rel');
  25.     $link_type = $link->getAttribute('type');
  26.     $link_href = $link->getAttribute('href');
  27. }
  28.  
  29. $feed_subtitle   = $gdata_cal_feed->subtitle();     //Equivalent to a RSS' channel description
  30. $feed_author_name   = $gdata_cal_feed->author->name();    //str
  31. $feed_author_email  = $gdata_cal_feed->author->email()//str email
  32.  
  33. //Now lets's spit out ENTRIES and their information
  34. foreach ($gdata_cal_feed as $ix => $cal_entry){
  35.     $cal_entry_id         = $cal_entry->id();            //str url
  36.     $cal_entry_title            = $cal_entry->title();      //str
  37.     $cal_entry_author         = $cal_entry->author->name()//str
  38.     $cal_entry_content      = $cal_entry->content();    //str
  39.     $cal_entry_email            = $cal_entry->author->email()//str email
  40.     $cal_entry_published       = $cal_entry->published();  //str date
  41.     $cal_entry_updated    = $cal_entry->updated();  //str date
  42.     $cal_entry_summary    = $cal_entry->summary();  //str
  43.     $cal_entry_visibility      = $cal_entry->{'gd:visibility'}['value']//str bool
  44.     $cal_entry_sendeventnotify  = $cal_entry->{'gCal:sendEventNotifications'}['value'];
  45.     $cal_entry_transparency     = $cal_entry->{'gd:transparency'}['value']//str
  46.     $cal_entry_event_status  = $cal_entry->{'gd:eventStatus'}['value'];   //str
  47.     $cal_entry_where            = $cal_entry->{'gd:where'}['valueString']//str
  48.     $cal_entry_starttime        = $cal_entry->{'gd:when'}['startTime'];  //str date
  49.     $cal_entry_endtime      = $cal_entry->{'gd:when'}['endTime'];  //str date
  50.     $cal_entry_reminder_mins    = $cal_entry->{'gd:when'}->{'gd:reminder'}['minutes']//str mins
  51.     $cal_entry_commentsfeedlink = $cal_entry->{'gd:comments'}->{'gd:feedLink'}['href']//str url
  52.    
  53.     $cal_entry_links = $cal_entry->link();
  54.     foreach ($cal_entry_links as $ix => $entry_link){
  55.         $entry_link_rel  = $entry_link->getAttribute('rel');    //str
  56.         $entry_link_type    = $entry_link->getAttribute('type');    //str
  57.         $entry_link_href    = $entry_link->getAttribute('href');    //str url
  58.         $entry_link_title   = $entry_link->getAttribute('title')//str
  59.     }
  60.                    
  61.     //category
  62.     $cal_entry_category = $cal_entry->{'category'}//Type Zend_Feed_Entry
  63.     $cal_entry_category_dom = $cal_entry_category->getDOM()