How To Write a Page Controller in PHP for Dynamic Content February 6, 2010
Posted by chris in : php, seo , add a commentThis how to will cover the topic of creating a dynamic content system. It’s a well known fact that when you come across a site like wikipedia that they don’t have an html file for each article. That would be insanity. It would be nearly impossible to display the file tree in an IDE and cumbersome to search through even with an OS that has a slick file system and powerful shell like Linux. Trust me, I worked on a site that created a unique page for each product on their site (they’ve since gotten with the times). So how can web browsers access a page like http://en.wikipedia.org/wiki/Mike_Tyson, when that file doesn’t exist. The application uses a combination of server-side code, database storage, and apache htaccess magic. Here’s how to do this.
Apache HTACCESS
This is the most important part of redirecting dynamic content. The .htaccess file is what makes the magic happen. What happens is a user requests http://en.wikipedia.org/wiki/Mike_Tyson, apache goes to process the request and does its thing. Normally apache would redirect this to a 404 error page because the file does not exist, but if it see’s the .htaccess file in the directory, then apache will follow the rules we defined in the htaccess. Our rule will tell apache that if the file is not found, to go to some other file. We will call this file mycontroller.php (because its the controller in our ModelViewController). Below is some example code to get your started:
Options -Indexes
Options +FollowSymLinks
DirectoryIndex index.php
ErrorDocument 404 /404.php
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ mycontroller.php [L,QSA]
</IfModule>
Recap:
1. We have /public_html/mydomain.com/wiki/.htaccess
This overwrites the Apache Web Servers default operating procedures.
2. We redirect the request to /public_html/mydomain.com/wiki/mycontroller.php
This contains the server side code that will handle our request for the Mike Tyson article.
The Database
Going in detail on this topic is beyond the scope of this article, but you’ll need some sort of database management system to store your article on Mike Tyson and the thousands of other articles. Of course there are other options like an XML file, but a database such as MySQL is the sanest approach for most sites.
Server Side Code
You’ll need some sort of server-side code running whether is ASP, JSP, or PHP. I’m a bit partial to PHP so lets roll with that. In mycontroller.php your code might look something like this:
$uriArr = explode('/',$_SERVER['REQUEST_URI']);
$article = $uriArr[2];
$article = urldecode($page); // in this case the article equates to Mike_Tyson
$sql = "SELECT * FROM article WHERE name = '$article'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
$page = mysql_fetch_assoc($result);
header('HTTP/1.1 200 OK');
header('Connection: close');
include_once 'mytemplatepage.php';
DIE():
}
else{
header('HTTP/1.1 404 Not Found');
header('location: /404.php');
header('Connection: close');
DIE();
}
This is asking our database for any records it has on the request Mike_Tyson. If a row is returned than we know we’ve found our article. We tell the browser that this is a 200 OK request. Then we include a file called mytemplate.php (this file is never actually seen by the browser). We set the record in the database to a variable array called $page. Our mytemplate.php file will look for this variable and begin populating the article. Lets see $page contains the following data: Title, Body, Image, and References. The mytemplate.php file might look something like this:
$title = $page['title ']; $body = $page['body ']; $image = $page['image ']; $references = $page['references ']; echo "<html><head><title>$title</title></head><body>"; echo "<h1>$title</h1>"; echo "<div class="mainImage">$image</div>"; echo "<p>$body</p>"; echo "<p>$references</p>"; echo "</body></html>";
Sweet! We can use the same template for a bunch of different articles, without having to create multiple files. Now if the user had searched for the following url: http://en.wikipedia.org/wiki/Mike_TysonIsEvil, we wouldn’t have an article on that. So instead the code would tell the browser this is a 404 Error and route the browser to the 404.php page.
This is an over simplified version of a dynamic content system, but it would work. If I was developing one of these on a professional level it would be complete with objects to handle requests, string cleaners to protect against SQL injection and XSS attacks, error logging, and the works! Let me know if you have questions I can answer and thanks for reading.
Optimizing Cnizz.Com For Page Speed and SEO February 3, 2010
Posted by chris in : seo , add a commentThis is the first installment of my SEO category. I’ve dabbled in SEO here and there every since I ran a semi-successful (but not successful enough) music site through 2006-2008. The site actually ranked highly for a few good SERPs and received over 10,000 unique visits per month. Though the site is a shell of its former self I still run adsense on it which brings in about $20 a month. Sighh, what could have been. In any case, I feel I’m qualified to talk about SEO to the limited audience this blog attracts.
I was just reading over @ SEOmoz that in 2010 page speed may be considered when ranking SERPs. I downloaded the google page speed for firefox plugin and decided to see where my domain sucked. The results are in:

86 out 100 isn’t too bad, at least its better than what my grades looked like in high school. Lets see what kind of optimizations I can make based off of Googles suggestions.
Image Optimizations
When the plugin says “Specify image dimensions” it’s just telling you that instead of having html for an image that is 50 x 50 like this: img src=”myimage.png” to instead specify its dimensions like this: img src=”myimage.png” height=”50″ width=”50″. Google also says serving scaled images is a no-no. Google become a bit angry because one of my images was 100×100, but I was scaling it in the HTML to be 50×50. Just open up your image editor (I use da GIMP cause I’m on Linux) and scale it to the dimensions you want. After these few modifications I reanalyzed my page and the plugin had bumped up my score to 90 out of 100. Woot! Thats an “A-” grade.
The next image optimization listed was the actual optimization of image compressions. Luckily the plugin will give you the optimized version and tell you how much space it will save. Just expand the “Image Optimization” box, click on the image, save it, and upload it to your server. This moved cnizz.com up to 91 out of 100.
Remove unused CSS
A lot of designers put their CSS into single file. Google advises against this and told me I could reduce the size of my CSS file by 19% (510 bytes) by removing CSS that was not used on the index page. Then something strange happened. Creating a second CSS file and only including that on pages were those classes were used caused by score to go down to 88 (remember I was at 91). Google penalized me for having multiple CSS files! I threw my hands up in the air on that one, marked it as nit-picky, and reverted back to my original CSS structure.
Leverage browser caching
This is the big one. I expect most sites to suffer from this. Its easy to resolve through the use of an HTACCESS file. I threw in the following code:
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|css)$"> Header set Cache-Control "max-age=3600" </FilesMatch>
This bumped me up to 94 out of 100. I could obtain 98 out of 100, by increasing the max-age to an insane amount of time. However on sites were the front page changes frequently such as a high volume e-commerce sites index page this is likely to be a bad idea. Just imagine if those thousands of users that just clicked through your adwords campaign were seeing last weeks special offers, yikes! However caching images that you know will not change unless there is a major site redesign is a good idea.
Conclusion
The google page speed plugin for firefox certainly gives you some great ideas for increasing the speed of your site and reducing the amount of bandwidth being pushed through your pipe. Lots of these suggestions can be implemented in a very short one day to one week project (depending on the size of your site). My advise is run the tool, but be cautious about the changes you make. Remember, you’re using this tool to potentially increase your listings for your targeted SERPs, but more importantly, this is a tool that should improve the experience of your sites users. As always there is balancing act between performance and features.
I welcome your comments
well my word press theme got hosed February 3, 2010
Posted by chris in : rant , add a commentI upgraded word press, thinking to myself “wow, this wordpress updater is really awesome.” Next thing I know the costume theme I created for my site was just gone. This really sucks and I don’t have time to fix it. So this blog will look like crap for a while. I don’t like how it doesn’t match the rest of the site now. Anyways one of my goals is to redesign this site anyways so this is just more motivation to do so. Now on to the blog post I was working on….arggh.
Multiple Monitor Software January 4, 2010
Posted by chris in : rant , add a commentCheck out http://www.mediachance.com/free/multimon.htm
Goals for the year December 31, 2009
Posted by chris in : rant , add a commentWhat are your goals for the year. We all like to make resolutions, I’ll just make goals, that way I don’t feel bad if I don’t make them. In no particular order I’ll list some goals I want to accomplish this year:
Become Zend Certified
I read over the certification guide and I am confident I could pass 80% of the test, it will look good on a resume (and for this site), and will just be kinda cool to say “yeah, I’m Zend Certified.”
Redesign Cnizz.com
Yup it could use a more modern personalized look. Same with this blog, but I won’t worry about that for a while.
Spend less
I went over my expenses and I have way too much frivolous spending. I’d like to cut this rampant expenditures by $100.00 per month and put that money in my savings account.
Get my side projects up
I have two of them. One is a lead generation site and the other is helping my friends with their online retail site.
Pay Off Debt
Luckily I don’t have a lot, just student loans and a car loan, but I would really like to pay off (or at least make a huge dent) in my car loan.
Take Guitar Lessons
I have an old acoustic, but don’t know many songs or chords. Would love to be able to play it more often.
How about you?
MooTools Table Sorter added to MooTools Plugin Repo December 23, 2009
Posted by chris in : rant , add a commentI’ve added my mootools table sorter to the newly created plugin repo created by mootools called, mootools forge. I’ll be enhancing the documentation over the holidays and adding much needed updates to the code. If you’re a mootools user or have been thinking about using mootools this is a huge step forward for the team over at mootools. The plugin site is much better than JQuery’s.
I’m also on twitter now.
The Four Core PHP Development Principles November 13, 2009
Posted by chris in : rant , add a commentWe’ve all written bad code. Look at the code you wrote 2 years ago, 6 months ago, or heck even yesterday. When I do this I find that I failed to follow my 4 core development principles. That’s okay we are not perfect, but we should always be striving to accomplish something more than just getting the job done when we program. Just getting the job done in a quick manner will almost always produce poor quality code that at best doesn’t scale and at worst isn’t secure.
1. Scalable
Big apps get more lovin’. If your code isn’t scalable, it probably sucks.
What do I mean by scalability? One way to look at scalability is how easy is it to add in new features to your application. The best way to create scalable code is through planning, understanding what you want the application to be when its complete, where you want the application to be in 3 years, and what other markets/tasks you might want the application to handle down the road.
MooTools Table Sorter version 0.9.5 October 13, 2009
Posted by chris in : ajax/dom/javascript , add a commentI’ve added some additional features to TableSorter (originally featured here). I fixed some bugs in the removeParameter function, added a removeAllParameter function, and added a reloadView function. The new version has nicer default CSS and provides you with a pretty default table reload feature.
Check out the demo page. Post any questions here please.
mysql get total rows in query with sql_calc_found_rows August 13, 2009
Posted by chris in : SQL , add a commentThe MySQL SQL_CALC_FOUND_ROWS function is a nice way to return how many rows were returned in the query. There has been a lot of discussion in the PHP.net entry on mysql_num_rows regarding this function. The debate centers around whether its more effecient to use MySQLs built in functionality or whether its more effecient to run the same query again using the COUNT() function.
For me, its hard to determine which way is better. Usually its better to leverage your database engine than code. There is not an easy way to tell how database cache plays into this either. I feel using SQL_CALC_FOUND_ROWS is the better option, it eliminates a few extra lines of code, and prevents you from having to update multiple queries. Whether there is a performance penalty in either case is debatable, if its even noticeable…
SELECT SQL_CALC_FOUND_ROWS * FROM tbl_customer WHERE entry_date > '2009-01-01';
In a separate query run this (I believe this is connection dependent, so they must be run in conjunction with each other within the life of the same connection).
SELECT FOUND_ROWS() as totalRows;
best way to load your JavaScript July 30, 2009
Posted by chris in : ajax/dom/javascript , add a commentInteresting article over at Ajaxian on loading your javascript code. I’m not sure this is the best way in all cases, but when you’re coding in a world of frameworks, multiple js files, wysiwyg editors, and framework plugins and widgets it definitely makes sense in many circumstances.