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.
Slides and an HTML reference version below. A sample application with all code examples is at https://github.com/jonathandean/SASS-and-HAML-FTW.
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.
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.
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
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.
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".
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.
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.
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
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
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.
#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:
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) && !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('&', $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:
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;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 “./”
I’ve tried a few different ways of doing friendly URLs in PHP and all have their advantages and disadvantages. For a good introduction and some other methods that don’t necessarily require an Apache server, take a look at this sitepoint article. I’ve used Method 2 there before (.htaccess Error Pages) but I don’t like what that does to your server logs.
For the method I use most often and am describing here, the credit goes to ex animo. He first showed me the .htaccess rewrite rule while we were working on a project at sunKING and I have only added a little of my own twist to it.
The basic idea is simple:
So let’s take a look at the .htaccess file you’ll have to make in order to redirect your web requests:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?permalink=$1 [QSA,L]
If you’re quick on the uptake you’ll notice that all requests except those that have a period in them will be redirected to index.php and that it will get the request URI as a parameter. The reason for not allowing the period is so that we can still access images and other static assets via their actual filename. You don’t necessarily have to do this but I think it keeps things cleaner when you don’t have to parse URIs for images as well. Not to mention that I can think of no good reason to have a friendly URL to an image or style sheet and can think of plenty of reasons not to.
Anyway, so what do we do with this? Well, we want to set up index.php to parse the URI being passed in and display the page we want. You can do this in any number of ways but here’s how I normally do my setup for most small sites. My simplified index.php file will look something like this:
<?php
define('INCLUDE_PATH', $_SERVER['DOCUMENT_ROOT'].'/../includes/');
ini_set('include_path', '.:'.INCLUDE_PATH);
// define the homepage
define('DEFAULT_PAGE', 'home');
// get the URI passed in via the .htaccess rewrite
$page = $_REQUEST['permalink'];
// set the page to be the homepage if none is given
$page = empty($page) ? DEFAULT_PAGE : $page;
// if the page doesn't exist, show an error page
$page = file_exists(INCLUDE_PATH.'pages/'.$page.'.php') ? $page : '404';
// I sometimes set page titles here to use a common header, but not necessary
switch($page)
{
case '404':
$pageTitle = 'page not found // ';
break;
case 'home':
$pageTitle = 'home // ';
break;
case 'about':
$pageTitle = 'about // ';
break;
case 'contact':
$pageTitle = 'contact // ';
break;
case 'another/page':
$pageTitle = 'another page // ';
break;
default:
$pageTitle = '';
}
require_once('header.php'); // common header
require_once('pages/'.$page.'.php'); // requested page
require_once('footer.php'); // common footer
?>
You can surely (and probably should) do a lot more processing here depending on your site’s needs, security concerns, etc. but this is the basic idea. Obviously, you want make sure those include (or require) statements reference the correct file locations. I usually simplify that by setting the include path as I have above.
Note that in the above example I have my includes directory outside of the public root so that the files aren’t directly web accessible. Some servers can’t do this (such as ones running Plesk) so for those you’ll have to modify that first line to be like this and put the includes folder in a public directory:
define('INCLUDE_PATH', $_SERVER['DOCUMENT_ROOT'].'/includes/');
So what’s left? Not really anything. All you have to do now is put your PHP files in the proper locations and you’re done. So with the example above you would put the file about.php in your includes/pages folder in order to get to that page via http://example.com/about . To get to http://example.com/about/me you would just put your me.php file inside of includes/pages/about/me.php .
In fact, in the time it took you to read to the bottom of this article you could have already had your site up. Not too shabby, eh?
Just to help you get started I’ve created a zip file that you can just extract an upload to your server. If you’re using Media Temple or other hosts that work similarly you can just upload the contents to the root folder of the website (so the folder that is named like yourdomain.com). The html folder in the zip is the public root (where you normally put your index.php or index.html file for your home page.)
If you’re using Plesk you’ll want to move things around just a little since it won’t let you include files out of the public root. Just put the files in the html folder (index.php and .htaccess) into your httpdocs folder and throw the includes folder in there as well. Then modify that first line that defines the INCLUDE_PATH constant for the new location as mentioned above.