All posts in All

An introduction to SASS and HAML

From my talk on learning HAML and SASS for Magma Rails 2011.

Slides and an HTML reference version below. A sample application with all code examples is at https://github.com/jonathandean/SASS-and-HAML-FTW.

Continue reading →

PostgreSQL 8.4 on Mac OS X 10.7 (Lion)

This should probably work for any version but 8.4 is what I needed and tested.

Continue reading →

delayed_job in Rails 3

I searched for how to use delayed_job and Rails 3 on Google last night and went down a little rabbit hole I thought I could try to help someone else avoid. I ended up at http://www.dixis.com/?p=335 which provided a great, but out of date, article on how to do this. It recommends using collectiveidea’s fork of delayed_job in the master branch, but as it turns out the latest in the master branch in is in flux at the moment. The ActiveRecord backend is currently being abstracted into it’s own gem (which is a great idea) but that means the generators to make the database tables are no longer there. It also in general seems not ready for prime time.

Continue reading →

jQuery Plugin: selectAll

I added a jQuery plugin that I wrote a while ago that turns a checkbox into one that selects or deselects other checkboxes on the page. Example HTML and CSS to follow.

Find it at https://github.com/jonathandean/jquery.selectAll

New jQuery plugin: Fix on scroll

I added a new jQuery plugin that will fix an element to the top of the browser window once you scroll past it, similar to the functionality of the actions bar in the newest gmail UI.

Find it at https://github.com/jonathandean/jquery.fixOnScroll

Update: The right sidebar (on this page only) should move down as you scroll past it in the browser window. Depending on your window size, you may need to shorten the height of your browser to see it. The code for this is simply:

$(document).ready(function(){
  $('#sidebar').fixOnScroll();
});

There are more usage examples on the README page of the git repository

Running older versions of Selenium RC and keeping Firefox 4

Some older versions of Selenium RC don’t work properly with the new Firefox 4 (we are using 1.0.3 I believe.) The best solution is to upgrade your version of Selenium to at least 1.0.4 I’m told, but we aren’t able to do that for our project. So here is a way you can run Firefox 3 and 4 on the same computer so that you can use Firefox 4 as your primary browser and allow Selenium to launch Firefox 3 (even while Firefox 4 is already running.) For the moment I’m short on time so you’ll have to refer to some external articles and change a few of the steps. Time permitting I will try to consolidate all steps into this article to make things easier to follow and just in case those articles become unavailable at some point.

Continue reading →

Unlearning and Relearning jQuery: Client-side Performance Optimization

Here are my slides from my presentation at Magma Rails. Please feel free to make suggestions, corrections or ask questions via the comments or using the contact page.

Continue reading →

Installing meld diff tool on OS X Snow Leopard (using fink)

Install fink

First we’re going to install fink as it will provide an OS X-ready version of meld for us (and quite a number of other UNIX programs as well). At the moment you’ll need to install fink from source for Snow Leopard (OS X 10.6). If you’re using another version of OS X there are binaries available for 10.1 to 10.5 on the main downloads page. The download for the source version is located at http://www.finkproject.org/download/srcdist.php. The latest version at the time of this writing is 0.29.10 and can be found directly at http://downloads.sourceforge.net/fink/fink-0.29.10.tar.gz. Download and save that file somewhere.

Continue reading →

Git tip: merging the latest version of one or more files from another branch

Today I was working in two separate branches in git and wrote a jQuery plugin that was useful to both branches. The problem was that I committed this new file along with changes to other files in order to use it. So I didn’t want to use cherry-pick to grab the commit because I didn’t want the other changes from that commit. There’s also the case where there are many commits involving that file in the other branch and you just want the most up to date version of that file. Turns out there’s a simple way to merge the latest version of a file (or even multiple files) from another branch into yours. Just follow this syntax:

git checkout <other branch name> <path(s) to file(s)>

Example of a single file:

git checkout new_feature public/javascripts/jquery.newplugin.js

Example for multiple files:

git checkout new_feature public/javascripts/jquery.newplugin.js public/stylesheets/jquery.newplugin.css

Then you can commit and you’ll have that file in your branch without causing any git ugliness.

Resource (and a little more detail) on Jason Rudolph’s blog.

Fixing blank pages after upgrading to WordPress 3

Today I finally clicked the auto-upgrade button to upgrade my WordPress site to the newest version, 3.0.1. I then noticed that I wasn’t seeing the content of a lot of my pages. I could still see the lists of posts but I wasn’t getting anything on a single post or normal page. I verified the data was in the database.

Here’s what my page.php looked like:

<?php get_header(); ?>
<div id="pageWrapper">
	<h2><?php the_title(); ?></h2>
	<?php the_content(); ?>
</div>
<?php get_footer(); ?>

This was all fine and dandy for WordPress 2.x but obviously wasn’t working for 3.0. Turns out the solution is quite simple. I just need to put the_content() back into "the loop":

<?php get_header(); ?>
<div id="pageWrapper">
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
		<h2><?php the_title(); ?></h2>
		<?php the_content(); ?>
	<?php endwhile; endif; ?>
</div>
<?php get_footer(); ?>

I’m not sure why the change but I suppose I should have always explicitly used "the loop". Maybe I was taking advantage of a bug this whole time? Or maybe this was an intentional change that I should have seen coming. At any rate, if you see your content missing after an upgrade, take a look at your theme and make sure the_content() is always inside "the loop".

Dynamic config files in Symfony

Don’t like the idea of manually setting certain values in your Symfony YAML configuration files? Or maybe, like in my case, you want the value of one setting to be set based on the value of a previous one, maybe a calculation of other values for instance. It may not be obvious at first but you can include PHP blocks in your config files. You just need to be a little careful about the line endings in order for it to work properly. If you take a look at your apps/application/config/settings.yml there’s already an example in there in how to achieve this:

dev:
  .settings:
    error_reporting: <?php echo ((E_ALL | E_STRICT) ^ E_NOTICE)."\n" ?>

Here’s a (silly) example of what you may want to put in your app.yml:

<?php $i = 10; ?>
all:
  numbers:
    option1: <?php echo ($i++) . "\n" ?>
    option2: <?php echo ($i++) . "\n" ?>
    default: <?php echo $i . "\n" ?>

Just note “\n” at the end of the line as this is important. Without it the newline character won’t be added and the resulting YAML will be malformed. Also be really careful not to put any spaces or anything in front of a PHP block that doesn’t output anything, such as the first line in that example since that will also be malformed YAML. Just always remember to think of what the output will look like and that it must be valid YAML.

Note: I’m using Symfony 1.4 and haven’t verified this in other versions.

A few good html5 references

I started playing with html5 and wanted to share some good resources I’ve found for anyone trying to get up to speed on the specs, browser support and code samples.

For a very detailed overview of everything html5 is (and isn’t) head over to diveintohtml5.org. The section entitled “What does it all mean?” is a great reference for all of the new elements, what they mean and how to use them. The site also has quite a lot of information on browser support, history of the working standard and all of new technologies html5 offers.

If you want to jump straight into some code html5reset.org gives you three different zip files to download. A barebones template, “the kitchen sink” template and the kitchen sink with very useful comments. I recommend grabbing the kitchen sink with comments, reading through the code and comments and then making your own template from scratch. Don’t be tempted to include the entire kitchen sink in your code – remember that less is more! Nonetheless, it’s a great reference to learn from and should get you up and running with html5 quickly. It’s also a great spotlight on some of the great scripts available to support html5 elements in older browsers, such as hosted versions of John Resig’s "HTML5 Shiv", The Modernizr script and Dean Edwards’ IE7/8/9 scripts.

If that’s too much reading for you to understand what browsers are supporting html5 today, jump on over to The Web Design Checklist for an excellent chart reference on browser compatibility. Just keep in mind that not seeing your site’s most popular browser in the compatible list doesn’t mean you can’t start using html5 today. There are lots of graceful degradation tricks and scripts out there (as mentioned in the above resources) that can get you looking forward to the future of the web.

Honorable mention goes to Coding A HTML 5 Layout From Scratch By Enrique Ramirez on Smashing Magazine for a quick barebones html5 layout.

I plan on writing an another article on html5 once I get a little farther with what I’m working on but wanted to share a few of the resources I’m using myself to get started. (Hopefully) more coming soon.

Dividing numbers in Ruby returning zero or an integer unexpectedly?

There’s a “quirk” about Ruby that I often forget when going back to it after a long period of time using other languages. If you divide two integers in Ruby then it’s going to give you an integer as a result. Consider the following:

some_int = 3
another_int = 2
answer = some_int / another_int  # answer is going to be 1 here

To fix this you’ll need to convert your integers to floats first. The following will work:

some_int = 3
another_int = 2
answer = some_int.to_f / another_int.to_f  # answer is going to be 1.5 here

the to_f function is going to convert the integers to floats and give you the float (decimal) answer.

Fixing slow FTP listing on CentOS 5.3 and safely reloading iptables config

I first went looking for a solution as to why connecting to FTP on my new CentOS 5.3 server was very slow. I found this post that had the answer: http://www.electrictoolbox.com/directory-listing-slow-ftp-server-centos/

The gist of it is to edit /etc/sysconfig/iptables-config and add the following:

IPTABLES_MODULES="ip_conntrack_ftp"

However, the big lesson here is that if you reload your iptables now you may end up losing a lot of your rules. In fact I did this and my website (and every other service) immediately was unable to connect. I was extremely lucky that I was just playing around a few minutes before with how to back up the existing rules. So before you do anything with iptables, run this first to export your currently active rules:

iptables-save -c > /etc/iptables-save

Now proceed to reloading your iptables-config:

/etc/init.d/iptables restart

Then make sure to re-apply the rules you saved with iptables-save by using iptables-restore:

cat /etc/iptables-save | iptables-restore -c

Now I don’t pretend to be any expert on iptables. I’m sure that someone very experienced with iptables will be able to tell that right away and maybe even provide a better solution. I just know that my limited experience tells me that the rules I have set in my iptables config files are less than what’s actually active right now. My guess (and I cannot confirm this) is that Plesk applied many of the rules I had in place. I had also applied a few of my own rules using the iptables command and I didn’t edit any config files so that was my first hint that what is actually running at the moment is not from config files alone.

So unless you are very experienced with iptables, do yourself a favor and use iptables-save before making any changes to your config files and/or restarting iptables.

References:
Directory listings slow with ftp server and CentOS
iptables-save
iptables-restore

Running PHP and MySQL with phpMyAdmin on OS X 10.5

Apache already comes pre-installed on OS X but PHP is not enabled by default. To enable PHP we need to edit our Apache config file by opening the Terminal and typing sudo nano /private/etc/apache2/httpd.conf and hitting enter (put in your admin password when it asks.) Type Control+W to bring up the search option and type php5_module and hit enter. Remove the # from the beginning of that line and then type Control+X to exit, Y to save when it asks, and Enter to overwrite the same filename.

Next, we want to create our PHP config file since it isn’t there by default. In the Terminal type cd /private/etc and hit enter, then type sudo cp php.ini.default php.ini and hit enter. This makes a copy of the default configuration we can use to get started with. We’ll use that later. Now you can start up Apache by going to System Preferences, Sharing and checking the Web Sharing box. If it was already checked, uncheck it and then recheck it again to restart Apache to accept our changes.

Now you need to install MySQL. Luckily, there’s already an install package available at MySQL.com so head on over there and download the latest stable version of 5.X. Now extract the zip, open the dmg and run the .pkg installer. I would also recommend double-clicking the .prefPane file for quick access to startup and shutdown commands without needing the Terminal. I don’t necessarily recommend installing the MySQLStartupItem package unless you really need it. In fact, you really shouldn’t leave MySQL or your web server running at all when you aren’t using it.

Once MySQL is installed you need to start it up. If you installed the preference pane (the .prefPane file) you can just go into System Preferences and then click MySQL. From there just click the button to get it started. Now we are going to want to set a password for the root user. To do that just open up the Terminal and type mysql . If it can’t find the mysql command we can add it to your path by editing your bash profile. Just type sudo nano ~/.bash_profile in the Terminal to edit the file, entering your admin password when it asks. Then add a line that looks like this: export PATH=/usr/local/mysql/bin:$PATH and type Control+X, Y, Enter to quit and save your changes. Then you’ll need to reload your bash profile by typing source ~/.bash_profile

Now you should be able to type mysql in the Terminal from any directory to connect to mysql. From the mysql> prompt type the following, substituting yourpassword with your desired password and then hit enter: set password for ‘root’@'localhost’ = password(‘yourpassword’); To make sure it was effective, log out by typing exit; and then enter and log back in again but this time we want to supply our credentials. So type the following to show that we want to log in using the root user and a password: mysql -u root -p

To make sure PHP can connect we need to edit our php configuration to know where the MySQL socket is located. For this type sudo nano /private/etc/php.ini from the Terminal. When the file opens type Control+W to bring up the search box and type in mysql.default_socket and hit enter. After the equals sign on that line enter /tmp/mysql.sock and and type Control+X, Y, Enter to quit and save your changes. Now we need to restart Apache for the change to take effect by going to System Preferences, Sharing and unchecking then rechecking the Web Sharing box. (Or via command-line if you wish.)

Now to install phpMyAdmin just download the latest and extract it into your Sites folder in your user account (/Users/username/Sites/) or the Apache root (/Library/WebServer/Documents/), whichever you prefer. Browse to that folder in the Terminal and type mkdir config to make the config folder and then chmod o+rw config to make it writable. Then browse to the setup folder in your browser, which would be http://localhost/~user/phpmyadmin/setup/ if you installed it in your user’s Sites folder or just http://localhost/phpmyadmin/setup/ if you put it in the Apache root. From there click the New Server button and then Save to take the defaults (unless you know other options you need) and then Save again in the Configuration File settings of the Overview page. Now you should be able to log into your server by going to either http://localhost/~user/phpmyadmin/ or http://localhost/phpmyadmin/ and entering your root username and password. It’s highly recommended that you create another user with fewer privledges to do most of your work, though.

If you also want to be able to use a .htaccess file you’ll need to go to the Terminal and type sudo nano /private/etc/apache2/httpd.conf to edit your Apache config file. Then type Control+W and search for AllowOverride. Change that option from None to All so that it reads AllowOverride All and then type Control+X, Y, Enter to quit and save your changes. Now we need to do the same for each user account. Do this by typing sudo nano /private/etc/apache2/users/username.conf and making the same change. If you aren’t sure what users there are you can type ls /private/etc/apache2/users/ . After you make the changes you’ll need to restart Apache again.

Some of this I did today and other parts of it I did a while ago so if anyone wants to give it a run through and let me know how it turns out that would be great. I know it could use some screenshots but those will have to come later since I was already done with this when I decided to write the instructions out.

My final word on this is to be mindful of security and make sure no one who shouldn’t can access any applications that are running. I would recommend shutting down MySQL and Apache when you aren’t developing to keep risks to a minimum. I’m not going to go into security since I assume that you know what you’re doing but it was worth mentioning again that any servers running on your machine are a potential security risk if you don’t know how to keep it safe.

References:

http://foundationphp.com/tutorials/php_leopard.php

http://dev.mysql.com/doc/refman/5.1/en/tutorial.html

http://wiki.phpmyadmin.net/pma/Setup

http://www.clagnut.com/blog/350/

Apple Time Capsule and Verizon Fios Actiontec router

I was pretty disappointed after my Verizon Fios install to learn that the Actiontec M1424WR modem/router combo only goes up to a G wifi signal. I’ve been using my Time Capsule with an N signal for a while and it’s great. I was even more disappointed to find that I wasn’t simply able to extend the Fios wifi network to use Time Capsule as an extra base station for my backups.

To help anyone who may have a similar problem, the solution was to connect the Time Capsule into one of the Ethernet ports on the Fios router so it would pick up the internet connection from there and create a separate wifi network on the Time Capsule. Now I actually have a better setup since I can force N-only mode on the Time Capsule so that my signal doesn’t degrade to G for everyone when a G device is connected (the newest Time Capsules can now support both simultaneously.) The G downgrade would happen more often than not because of my wife’s older Mac and my iPhone.

The recipe:

  1. Connect an ethernet cable between one of the numbered ports on the Fios router and the incoming WAN port of the Time Capsule
  2. Open the AirPort Utility and click on Manual Setup with your Time Capsule selected
  3. Click on the Internet icon at the top
  4. Under the Internet Connection tab change Connection Sharing to Off (Bridge Mode). I’m not sure if this is necessary but it worked for me and sounds like a good idea
  5. Click Update to reboot your Time Capsule

After this setup I have a B/G wifi network that everyone else will use in the house, including my Fios TV boxes, and another N-only wifi network that my MacBook Pro can connect to for the internet and Time Machine backups. This also allows me to make my Time Machine backups even more secure because I never have to give someone else access to the wifi information.

By the way, the Fios TV menus are way better looking and easier to use than Comcast. I haven’t looked at the on-demand service a lot yet but at first glance it looks much better too. I haven’t really noticed the internet being faster but that’s probably because the bottleneck will continue to be the servers I connect to and not my connection to the internet. If I don’t lose my internet connection for 30 minutes at a time randomly then I’ll know for sure that Fios internet is better too :)

Fios internet speed test results are below.

Time Capsule wifi:

Your download
speed is:
7.543 Mbps
Your upload
speed is:
5.957 Mbps

Actiontec wifi:

Your download
speed is:
7.601 Mbps
Your upload
speed is:
5.033 Mbps

Actiontec wired Ethernet:

Your download
speed is:
7.845 Mbps
Your upload
speed is:
5.967 Mbps

Apache rewrite rules to force secure/non-secure pages

If you’re running an Apache server there’s no need to hard code your links to force https/http or write server-side code. A few simple rewrite rules will allow you to redirect your secure pages to https and your non-secure pages back to http. We’ll just check the server port to see if it’s using secure port 443 and redirect the page accordingly.

For instance, to redirect the checkout section to use https just use the following in your httpd.conf file (or vhost.conf if using Plesk):

<Directory "/var/www/html">
RewriteEngine on
Options +FollowSymLinks
Order allow,deny
Allow from all
RewriteCond %{SERVER_PORT} !^443$
RewriteRule \.(gif|jpg|jpeg|jpe|png|css|js)$ - [S=1]
RewriteRule ^checkout(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
</Directory>

Of course, you need to make sure that the directory path is valid for your setup. This will force http://www.example.com/checkout to redirect to https://www.example.com/checkout

If you want multiple pages change the RewriteRule to something like:

RewriteRule ^(checkout|login)(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Just separate the page/folder names you want with the pipe (|) character. Read up on your regular expressions if this doesn’t make sense to you.

The first 4 lines are necessary Apache options we need to use for this to work properly. You can read the Apache manual for more information on those. The RewriteCond is testing if the server port is not 443, meaning we are not requesting via https. The first RewriteRule will ensure that files loaded within the page such as images, CSS, and JavaScript are loaded using the same protocol as the page itself. It matches on those file extensions and then uses the [S] (skip) flag to skip the next rule. This will help to avoid mixed content warnings in browsers. The list isn’t comprehensive so be sure to add to it as necessary. The RewriteRule under that uses a regular expression to test if our URI starts with checkout (or login in the second example) and if so it redirects the request to the same URL but this time using SSL. The [L] flag means that rewrites will end on this rule and the [R] flag means that you redirect the page so that the address changes in the browser. Removing the [R] flag will cause the page to be served via https but the URL to still show http.

This is all well and good but it’s only half of the equation. Once a user leaves a secure page then we should also be able to forward them back to regular http. To do this we just basically set up the reverse of the RewriteCond and RewriteRule:

RewriteCond %{SERVER_PORT} ^443$
RewriteRule \.(gif|jpg|jpeg|jpe|png|css|js)$ - [S=1]
RewriteRule !^(checkout|login)(.*)$ http://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Notice that instead of checking to see if we are not using port 443 in the RewriteCond we are checking to see if we are using it. Then in the RewriteRule we are making all pages that are not checkout or login redirect to http.

I’m pretty sure if you are using httpd.conf or a .htaccess file you can put these two lines directly below the original ones inside of the <Directory> block but I haven’t tested that. Since I’m using Plesk I needed to put the original block in my vhost.conf file (used for configuration of non-secure pages) and the entire block again but this time with the second set of rules in my vhost_ssl.conf file (used for configuration of secure pages). Also, if you are using any of the .conf files you will need to restart apache for your changes to take place.

And just as a final note, these steps will not help you in setting up your SSL certificate. You will already need to have that set up and functional before using this.

References:
Apache mod_rewrite manual
Ask Apache rewrite tips
whoopis.com tutorial
My original post with this answer on Stack Overflow

Search engine friendly URLs in PHP and Apache, Take 2

A while back I posted this article about friendly URLs in PHP and Apache. Today I’d like to update that a little to not only show another method but also to enhance it a bit. When we’re done we’ll have search engine friendly URLs that look like the ones that Blogger uses.

Why? Because search engines tend to penalize dynamic URLs in search result rankings so we want ours to appear as static as possible. Now I know that search engines have come a long way in indexing dynamic content but every little bit helps. So as long as the setup is easy (and it is) we may as well put in that tiny bit of extra effort. Why would static URLs get a higher ranking? I assume because creating a static page takes just a little more effort than a dynamic one and therefore you could argue that the content is likely to be of higher quality. Also, the content isn’t going to be compromised by spam bots that are mass posting or even stupid humans that are (mass) posting.

For an easy example, I’ve listed 5 URL formats that are common and could likely serve the same content. They are in order with the most search engine friendly at the top.

  1. http://www.example.com/post/title-of-post.html
  2. http://www.example.com/post/title-of-post
  3. http://www.example.com/post/654123
  4. http://www.example.com/post.php?id=654123

#3 beats #4 for two reasons. The first is that #4 is obviously dynamic content based on the fact that it is passing a parameter whereas #3 could actually be pointing to the static file post/index.html or post/default.htm. The other reason is that id is considered an especially obvious parameter to dynamic content and is often ignored when indexing. Using post.php?postId=654123 would be slightly better.

#2 is a huge leap over #3 because it actually includes the title of the post in the URL. Of all the things you can do to improve SEO, including your search keywords in the URL is going to give you the best result (and even better if the keyword is in your domain name!) #1 is just a little better still because adding that .html extension really enforces the appearance of being static content. As far as the crawler is concerned there is no way to tell that URL is dynamic.

So how do we make this happen? Well if you’re using PHP and Apache 2 you have a few options. (Note, Apache 1 will not work here because it doesn’t support the “look back” method that allows Apache to keep looking back in the URL until it finds our file. Without that it would only be able to find /post in the /post/title-of-post/ directory rather than in the root which is where it actually is. That may make more sense later.)

I recently modified Method 3 of this sitepoint article to get set up quickly with the scheme. It’s not perfect but it is pretty fast and easy to get up and running with for small sites. If you have a lot of dynamic pages then you may want to combine this method with the URL rewrite method I posted about previously so that you don’t have to create lots of files without extensions and update your Apache configuration for each. I like this method because it’s easier to mix friendly URL pages with normal directories. I say that because the regex used in the other method requires that you have a file extension for accessing a normal file directly. So it will ignore /somedir/images/img.jpg and /somedir/index.php but it will try to parse /somedir/example/ which can be a bit of a pain. With this method we’re only going to worry about particular dynamic files and let the rest operate as usual. A drawback of this method is that you can’t use it on your root directory. For instance you can’t have http://www.example.com/dynamic-parameter.html. It would have to be something like http://www.example.com/processor/dyanamic-parameter.html.

Now to get down to it. We’re going to do a few things here:

  • Create or modify our .htaccess file to tell Apache that certain files should be processed as PHP, even without an extension (or you could edit your vhost.conf file if you use Plesk or even your main Apache config if you feel comfortable)
  • Either remove the .php extension from our dynamic page or create a new file with the same name and no extension and use require_once() to include the .php version
  • Add some PHP to parse our URI and set variables we can use to load the dynamic content

So for the first item we’re going to open or create a .htaccess in our web root (or whatever folder we want to contain the dynamic pages.) If you only have one dynamic page, say post.php, you’d do something like this, substituting “post” with the name of your dynamic page (minus the .php extension.)

<Files post>
AcceptPathInfo On
ForceType application/x-httpd-php
</Files>

If you have multiple pages then use filesMatch instead of Files and separate each file with a pipe character (|):

<filesMatch "post|blog|login|logout">
AcceptPathInfo On
ForceType application/x-httpd-php
</filesMatch>

Basically what we’re doing here with ForceType is telling Apache that these are PHP files and to process them as such. Typically, the .php extension gives it away but we don’t want that here.

Now like I said above, you can either remove the .php extension from your file or create a new file and include the .php version. If you are converting existing pages to use this method I’d recommend leaving your .php version in tact in case of bookmarks or indexed pages. So alongside "post.php" you’d create the file "post" with this in it:

<?php
require_once('post.php');
?>

So now we have the option of getting to http://www.example.com/post.php by just using http://www.example.com/post and leaving off the file extension. The next thing we need to do is parse the rest of that URL and do something with it. You can do this a lot of ways but I kind of like options so I wrote a pretty generic function that will just give us some variables to work with. Cutting right to the chase:

<?php

$uriParts = null;
$dirsToRoot = 0;
$pathToRoot = '';
$linkToRoot = '';
$requestURI = '';
$requestParamString = '';
$requestParams = null;
parseRequestURI();

function parseRequestURI()
{
    global $uriParts;
    global $requestURI;
    global $requestParamString;
    global $requestParams;

    $uriParts = explode('?', $_SERVER['REQUEST_URI']);
    if(is_array($uriParts) &amp;&amp; !empty($uriParts[1]))
    {
        $requestParamString = $uriParts[1];
        $requestURI = $uriParts[0];
    }
    else if(is_array($uriParts))
        $requestURI = $uriParts[0];
    else
        $requestURI = $_SERVER['REQUEST_URI'];

    if(!empty($requestParamString))
    {
        $requestParams = array();
        $paramPairs = explode('&amp;', $requestParamString);
        if(is_array($paramPairs))
        {
            foreach($paramPairs as $paramPair)
            {
                $paramParts = explode('=', $paramPair);
                $requestParams[$paramParts[0]] = $paramParts[1];
            }
        }
        else
        {
            $paramParts = explode('=', $paramPairs);
            $requestParams[$paramParts[0]] = $paramParts[1];
        }
    }

    $uriParts = explode('/', $requestURI);
    if(is_array($uriParts))
    {
        if(empty($uriParts[0])) array_shift($uriParts);
        if(empty($uriParts[count($uriParts)-1])) array_pop($uriParts);
    }
    if(substr($uriParts[count($uriParts)-1], -5) === '.html')
        $uriParts[count($uriParts)-1] = substr($uriParts[count($uriParts)-1], 0, -5);

    setPathToRoot();
}

function setPathToRoot()
{
    global $uriParts;
    global $dirsToRoot;
    global $pathToRoot;
    global $linkToRoot;

    $dirsToRoot = count($uriParts)-1;

    for($i=0; $i<$dirsToRoot; $i++)
        $pathToRoot .= '../';

    $linkToRoot = empty($pathToRoot) ? './' : $pathToRoot;
}
?>

I think the easiest way to use this is to just define this script as an auto prepend file so that it runs at the beginning of every PHP file. You can do that by adding the following line to your .htaccess file:

php_value auto_prepend_file /path/to/file.php

If you’re going the auto prepend route make sure you have no whitespace characters outside of the <?php and ?> or you could end up with HTML validation issues. You don’t want whitespace showing up before your DOCTYPE declaration!

Anyway, this will give you access to the following variables on every PHP page:

  • $requestURI (String): The requested URL (without your domain name) not including any request parameters
  • $requestParamString (String): The full key/value pair request parameter string after the ?
  • $uriParts (Array): An array of the individual parts of $requestURI. You are mostly going to use this to load your dynamic content. If the last entry has a .html then it will strip it out.
  • $requestParams (Array): An associative array of the key/value pairs of $requestParamString
  • $pathToRoot (String): Prepending this to a relative path will help resolve it properly for you. Used for including CSS and other files (see below)
  • $linkToRoot (String): Just like $pathToRoot but is used for linking to other pages (see below)
  • dirsToRoot (Integer): The number of directories your browser will think you are from the root

Here are a few examples of what those variables will look like for different types of URLs:

http://www.example.com/post/something

$requestURI='/post/something'
$requestParamString=''
$uriParts=Array ( [0] => post [1] => something )
$requestParams=
$pathToRoot='../../'
$linkToRoot='../../'
$dirsToRoot=2

http://www.example.com/post/something.html

$requestURI='/post/something.html'
$requestParamString=''
$uriParts=Array ( [0] => post [1] => something )
$requestParams=
$pathToRoot='../../'
$linkToRoot='../../'
$dirsToRoot=2

http://www.example.com/post/something/more.html?name=jon&city=pittsburgh

$requestURI='/post/something/more.html'
$requestParamString='name=jon&amp;amp;city=pittsburgh'
$uriParts=Array ( [0] => post [1] => something [2] => more )
$requestParams=Array ( [name] => jon [city] => pittsburgh )
$pathToRoot='../../../'
$linkToRoot='../../../'
$dirsToRoot=3

http://www.example.com/help

$requestURI='/help'
$requestParamString=''
$uriParts=Array ( [0] => help )
$requestParams=
$pathToRoot=''
$linkToRoot='./'
$dirsToRoot=0

I think you can get the idea but a few things to point out here. First, the .html extension has no effect on the $uriParts string which is what we’re going to use to get our dynamic variables. Second, you probably would never pass the query string portion after the ? but I added it for completeness.

The purpose of $pathToRoot and $linkToRoot may not be entirely clear at first. It’s there in order to help with a relative path issue you may run into. The reason being is that the browser has no idea that /post is your PHP file and that your currently directory is actually the root of the site (or /). As far as it’s concerned, you’re in the folder /post/something/. So say you had an images folder in your site root alongside post.php. Typically you could just refer to it using just images/imagename.jpg and that relative path would resolve properly for you. However, your browser thinks you are in the /post/something/ directory so it’s going to think you mean /post/something/images/ rather than /images. Sure, you could just use the path /images/imagename.jpg but that only works if your application is at the site root. What if you want to move the site into a subfolder on another server? Or, like in my case, you want to use the Site Preview function in Plesk for your client but the path contains several subdirectories before your root? All you have to do is change images/imagename.jpg to <?php echo $pathToRoot; ?>images/imagename.jpg it will give you the correct relative path. Sure it can be a pain to print that out everywhere but it was a life saver for me to be able to have that kind of portability. (Of course this is great for including style sheets and JavaScript too.) The only difference between $pathToRoot and $linkToRoot is that when $pathToRoot would normally be an empty string (see the last example above), $linkToRoot will be “./”. When including CSS the empty string would basically indicate the current directory which is fine. For a link the empty string actually indicates the current page so we need to use “./” to explicitly indicate current directory so that the link actually takes us somewhere.

The last part of this puzzle is to do something with those dynamic URLs. Of course, that part is completely up to you. You essentially have two choices as I see it. You can either pass only the parameter values you need and always pass them in a particular order (such as /post/jon/2008-12-04/search-engine-urls) or you can pass your parameters as pairs that come in any order (such as /post/title/search-engine-urls/username/jon/date/2008-12-04). In most cases I prefer the first method but the second can be useful for pages where you don’t know all of the parameters being passed. In that case the even indexes of $uriParts will always be the parameter names and the odd indexes will always be the values. Or I guess you can do it the other way around too. The point is that this will get the data to you and now you just have to make something meaningful out of it.

This should go without saying but don’t forget to always escape any values being passed to a page before it interacts with your database. Take all precautions you normally would in a dynamic page!

Update 12/14/2008: Removed a test for ‘/’ as the last character in setPathToRoot(). All URLs are now treated the same way.

Update 1/24/2009: Added $linkToRoot to solve an issue in some cases where $pathToRoot would be an empty string. This works well for including CSS files but not good for making a link to the home page. $linkToRoot is the same value as $pathToRoot except when $pathToRoot is an empty string. In that case $linkToRoot will be “./”

Another way to fix washed out images from Photoshop’s Save for Web

I had some trouble today with washed out images when using Save for Web in Photoshop and thought I should share. In the past I’ve been able to solve this by unchecking the Convert to sRGB option but that didn’t cut it this time. In case you aren’t familiar, you can find that option by clicking the more options arrow to the right of the Preset drop down menu.

Convert to sRGB

After some poking around I came across <a href=”http://www.gballard.net/psd/saveforwebshift.html”>this interestingly formatted article</a> on the issue. Unfortunately the solutions there didn’t work for me but it did point me in the right direction. It turns out my color profile was set to Working CMYK and not RGB. (You want CMYK for print, not for web.) Anyway, all I had to do was go to Edit -> Convert to Profile and select Working RGB instead.

Convert to Profile

After that my Save for Web images looked just as I designed. There is one big drawback of this though. After converting the profile it flatted my file so make sure you don’t save and close the file too quickly and lose your layers. After saving for web I stepped back in history a few steps to get my layers back and saved it again to be safe. It’s not a big deal for me in this case because I only need to save for web once but I would have to do this step each time. I suppose the moral of the story is to check your color profile before you begin designing so that you don’t run into this mess in the end. If anyone has a better solution that doesn’t flatten your file I’d love to hear it.

The nupting of the nuptuals

Our wedding