Skip to Content

Aarron Walter

XHTML | CSS |

Archive for the 'PHP' Category

Parsing RSS Using Magpie and Ajax

29 Dec . 2006

DMXZone.com has recently published an article of mine explaining how to parse RSS feeds using an open source PHP library called Magpie, and Ajax to handle the loading of the feeds. The feed reader is scalable to display as many or as few feeds as needed using an array to conveniently configure the script. If JavaScript is disabled or unavailable in the browser, the script gracefully degrades to offer a manual method of loading the feed headlines to the page rather than becoming disabled because of the Ajax calls that load them normally. Ajax is used in this example because fetching and parsing many feeds from many sources can result in an excessive page load delay as the script waits for all results to arrive. Using Ajax, you can display the headlines for each feed as they are received, resulting in an improved user experience.

You can take a look at the finished example, and download the code archive to see how it works.

Displaying File Icons for Downloads With PHP

14 Dec . 2006

I've worked on a few projects where a client had a series of files they wanted to offer as downloads, and the file types were all different. It's nice to show users what type of file they are downloading with an icon that represents that format. To do this, I store the file info in a table that might look something like this:

Files Table

The $_FILES super global variable gives you access to all of this useful information about your file when it is uploaded, and storing it in the table along with the file name and date posted makes looping through them to display on a file download page convenient and easy. If your file form tag was called "newFile", here's what your SQL statement might look like to store the record in your database:

PHP:
  1. $sql = "INSERT INTO filesTable SET fileTitle='".$_POST['fileTitle']."', fileName='".$_FILES['newFile']['name']."', fileSize='".$_FILES['newFile']['size']."', fileType='".$_FILES['newFile']['type']."', datePosted='".time()."' ";

With the file type stored, when you pull the records out for display, you can use the fileType field to generate an image tag with the
corresponding file type icon. I wrote a simple function to handle this for me that I keep in an external file, and simply pass it the fileType and fileName strings to get the correct image tag. Here's what that looks like:

PHP:
  1. <?
  2. function icon($file, $filename){
  3.  
  4. // Determine File Type
  5. // See list of all possible mime types at http://www.webmaster-toolkit.com/mime-types.shtml
  6. switch( $file ){
  7.  
  8. case "text/html": $file = "html.gif"; $alt = "HTML File"; break;
  9.  
  10. case "text/shtml": $file = "html.gif"; $alt = "HTML File"; break;
  11.  
  12. case "image/pjpeg": $file = "jpeg.gif"; $alt = "Progressive Jpeg Image"; break;
  13.  
  14. case "image/jpeg":$file = "jpeg.gif"; $alt = "Jpeg Image"; break;
  15.  
  16. case "image/png": $file = "png.gif"; $alt = "PNG Image"; break;
  17.  
  18. case "image/gif": $file = "gif.gif"; $alt = "GIF Image"; break;
  19.  
  20. case "image/tiff": $file = "tiff.gif"; $alt = "Tiff Image"; break;
  21.  
  22. case "application/pdf": $file = "pdf.gif"; $alt = "PDF File"; break;
  23.  
  24. case "application/word": $file = "word.gif"; $alt = "Word Document"; break;
  25.  
  26. case "application/msword": $file = "word.gif"; $alt = "Word Document"; break;
  27.  
  28. case "application/powerpoint": $file = "excel.gif"; $alt = "Excel Spreadsheet"; break;
  29.  
  30. case "application/excel": $file = "powerpoint.gif"; $alt = "Powerpoint Presentation"; break;
  31.  
  32. case "text/plain": $file = "txt.gif"; $alt = "Plain Text File"; break;
  33.  
  34. case "application/zip": $file = "zip.gif"; $alt = "Zip Archive"; break;
  35.  
  36. case "application/x-stuffit": $file = "sit.gif"; $alt = "Stuffit Archive"; break;
  37.  
  38. case "application/x-msdownload": $file = "exe.gif"; $alt = "Executable"; break;
  39.  
  40. case "application/octet-stream":
  41. // Find Out If File Is PSD
  42. if( eregi(".psd",$filename) ){
  43. $file = "psd.gif"; $alt = "Photoshop Document";
  44. }elseif( eregi(".icc",$filename) ){ // Find Out if File Is ICC
  45. $file = "icc.gif"; $alt = "ICC Profile";
  46. }else{
  47. // Use Generic Icon
  48. $fileicon = "doc.gif"; alt="Unknown File Type";
  49. }
  50. break;
  51.  
  52. default: $file = "file.gif"; $alt = "Unknown Tile Type"; break;
  53.  
  54. }
  55.  
  56. $imgTag = "<img xsrc=\"images/$file\" alt=\"$alt\" />";
  57.  
  58. return $imgTag;
  59.  
  60. }
  61. ?>

The function is really just a big switch statement looking at the fileType string. The reason I pass the fileName string as well is because certain files like PSDs, and color correction profiles (ICC), share the same MIME type. Actually there are a lot of file types that share the "application/octet-stream" MIME type, so checking the file's extension can provide a means of determining what kind of file it really is. Note, this is not a sure fire solution if the file does not have an extension or has the wrong one. If the function gets stumped, it returns a generic file icon instead. Here's how you would use it:

PHP:
  1. <?
  2. // include fileIcon function
  3. require_once('inc/fileIcon.php');
  4.  
  5. $sql = "SELECT * from filesTable ORDER BY datePosted";
  6. $result = mysql_query($sql);
  7.  
  8. <ul>';
  9. while( $row = mysql_fetch_array($result) ){
  10.     <li><a xhref="files/'.$row['fileName'].'">'.icon($row['fileType'],$row['fileName']).' '.$row['fileTitle'].'</a></li>
  11. ';
  12. }
  13. echo '</ul>
  14. ';
  15. ?>

You could easily extend the icon function to recognize many other formats just by adding new cases. To see a complete listing of MIME types visit http://www.webmaster-toolkit.com/mime-types.shtml. You can download a good starter set of file icons here: File Icons

Dynamic Select Menus With PHP

12 Dec . 2006

When building content management systems, or most any web application, you often need to generate select menus dynamically by querying a database. A Select menu offers a user a set of predefined options to choose from, and prevent possible input errors that could occur if you instead gave the user a text field to type their selection, resulting in typos or selection of an option that is not available. A perfect example is when you have some list of categories stored in a table, and you need to create a form that allows a user to add a new record in a particular category. Here's what your table may look like:

Categories Table

A unique category Id is used as the primary key, creating a practical method of referencing a category. To query this table and generate a select menu, we can use a while loop like this:

PHP:
  1. <?
  2. $sql = "SELECT * FROM categories ORDER BY CategoryTitle";
  3. $result = mysql_query($sql);
  4.  
  5. echo '<select name="category" id="category">';
  6. while( $row = mysql_fetch_array($result) ){
  7. echo '<option value="'.$row['CatID'].'">'.$row['CategoryTitle'].'</option>';
  8. }
  9. echo '</select>';
  10. ?>

Notice that the select tags need to be written before and after the loop, so you don't end up with multiple menus, but just one menu
with many options. This approach is practical for future maintenance too, as you can simply add a new category to your database, and the interface will include it automatically.

The above example works great for building a menu on an add page where the user has not yet selected an option and stored it in a database,
but if you were creating an edit page you would need to have the user's previous selection already shown in the menu.to do this you would need to dynamically write in the selected="selected" attribute/value pair in the option tag for the category selected. Assume we have an articles table that has a CatID field that relates to our category table. To find out which option was selected we'll compare the CatID in the articles table and the CatID in the categories table as we run a loop to build the menu. We'll need to run two queries, one to get the articles record (in this demo I'll hard code in the id of the article we want) and one to get the categories.

PHP:
  1. <?
  2. $sql = "SELECT * FROM articles WHERE id='5'";
  3. $article_query = mysql_query($sql);
  4. $article = mysql_fetch_array($article_query);
  5.  
  6.  
  7. $sql = "SELECT * FROM categories ORDER BY CategoryTitle";
  8. $category_query = mysql_query($sql);
  9.  
  10. echo '<select name="category" id="category">';
  11. while( $category = mysql_fetch_array($category_query) ){
  12. if( $article['CatID'] == $category['CatID'] ){ $selected = ' selected="selected"'; }
  13. echo '<option value="'.$category['CatID'].'"'.$selected.'>'.$category['CategoryTitle'].'</option>';
  14. }
  15. echo '</select>';
  16. ?>

The $selected variable stores our attribute/value pair needed to preselect the user's option stored in the database, and will be empty if the condition was not met, thus leaving the option tag untouched.

Yet another common, dynamic select menu scenario is displaying date selections for years, months, or days. I create an external arrays file that has associative arrays of common lists such as this. Here is what such a file might look like. You could also add things like credit cards your e-commerce system accepts, and a list of countries for shipping information forms. Looping through associative arrays like this is a little different.

PHP:
  1. <?
  2. require_once('arrays.php');
  3.  
  4. echo '<select name="month" id="month">';
  5. foreach($year as $key=>$value){
  6. echo '<option value="'.$key.'">'.$value.'</option>';
  7. }
  8. echo '</select>';
  9. ?>

A foreach loop is the most convenient approach for associative arrays, giving you easy access to the key and the value of each item in the array.

There are an infinite number of applications for these examples, whether you are building a contact form or an entire content management system. Hope you find them useful!

Extending the Ajax Mailing List Sign Up System

06 Nov . 2006

A couple of my readers from my recent SitePoint article have asked me about how they could extend the Ajax mailing list sign up system to receive further inputs like the user's name and phone number. It's actually pretty simple. If you have additional fields in your form, just modify the parameters string in mailingList.js. Here's an example:

var pars = 'address='+escape($F('address')) + '&firstName='+escape($F('firstName')) + '&lastName='+escape($F('lastName')) + '&phone='+escape($F('phone'));

You can see that you can append as many or as few inputs from your form by just extending the GET string passed to the PHP script. Notice I've added the "&" before the next parameter names as is required in any GET string with more than one variable included. Of course you would need to adjust your MySQL table to include these fields, and change storeAddress.php to receive the values as well.

$address = $_GET['address'];
$firstName = $_GET['firstName'];
$lastName = $_GET['lastName'];
$phone = $_GET['phone'];

$addresscheck = mysql_query("SELECT * FROM mailinglist WHERE email='" . $address . "', firstName='" . $firstName . " ', lastName='" . $lastName . "', phone=' . $phone . "' ");

It's also quite easy to modify this technique to work for things like contact forms, or user input in a CMS by simply adjusting your form, and the references to the field names. The principles are still the same.

If you are interested in other useful Ajax tools, you may want to check out Dustin Diaz's Ajax contact form. It's pretty clever, and packed with nice effects, but seems to struggle to work in Opera. It's a pretty sophisticated example of a contact form.

A word of caution, it's pretty easy to get swept up by the allure and ease of implementation of many Ajax/DOM scripting tricks. Always ask yourself how it benefits or hurts the user experience. If you find yourself adding features because they are cool, yet they negatively impact findability, accessibility, or cross-browser use then you probably should reconsider. James Edwards has written a sobering article about Ajax and screen readers (lump search engine spiders in that group too as they are equally as blind) that may bring you back down to earth about the Ajax trend. I should also mention that my article is actually backwards compatible for those without JavaScript enabled, giving us the best of both worlds. The article also uses Ajax specifically to enhance the user-experience by making the impulse action of signing up for a mailing list faster and more convenient.

Getting Started/Further With Ajax and PHP

01 Nov . 2006

Beginning Ajax with PHP: From Novice to Professional (Pro)There are some good books on the market to help introduce you to the ways in which Ajax and PHP can work together to create user-friendly web applications. Apress recently released a book by Lee Babin entitled Beginning Ajax with PHP: From Novice to Professional. The book does a good job of introducing key concepts by way of useful examples that solve common problems. It's currently my favorite for bridging the gap between the two technologies.

SitePoint also has a nice book on Ajax entitled Build Your Own Ajax Web Applications. This book is focused specifically on Ajax, not so much about connecting client-side to server-side scripts.