Pretty URLs: Pretty Easy!

Tweet

Back when I wrote the third edition of Build Your Own Database Driven Web Site Using PHP & MySQL, it was still acceptable (though certainly unfashionable) to lump all of the code together to generate a web page into a single file, and then use a URL naming that file to access the page.

PHP has moved on. These days, a developer that builds web sites that way is unlikely to gain a job (except perhaps one that pays poorly). Developers are expected to organize their code into multiple files, and URLs containing file names like index.php are definitely on their way out.

Experienced developers will use finely-crafted frameworks and web server configurations to convert so-called pretty URLs like http://www.example.com/thingy/. No ".php" advertising the fact that the site is built in PHP, no specific filename at all. URLs like this one are designed to be as simple and memorable as possible.

For the fourth edition of the book, I wanted developers to make a habit of this earlier, without forcing them to fiddle with their server configuration, or learn a complex PHP framework.

The easiest possible way I could find to produce pretty URLs was to take advantage of a feature built into every PHP-equipped web server out there: a URL that points to a directory on the server will automatically run a PHP script named index.php sitting in that directory.

With that in mind, here’s how all of the examples in the book from Chapter 3 onward are structured:

  • A folder
    Everything goes inside a folder, whose name is the only visible part in the URL. So if the example displays "thingies", you would start by creating a folder named thingies, and the URL of the example would be http://www.example.com/thingies/
  • A controller, index.php
    When a browser requests the example’s URL, the server will automatically run the index.php script contained in the folder. This file is called the controller, and contains all the logic for handling browser requests and performing tasks in response.
  • Include files, like db.inc.php
    Pieces of code that will be useful in more than one example are pulled out of index.php and placed in separate PHP files. This is basic stuff for PHP veterans, but it’s a valuable coding technique that was covered much later in the third edition, in Chapter 12. Now it’s in Chapter 3.
  • Template files, like thingy.html.php
    Once the controller (with the assistance of one or more include files) does all the work, it must prepare a web page to send back to the browser in response. Rather than slopping all the HTML code into index.php (which is what we did all the way through the third edition of the book), the fourth edition uses a separate file for the HTML code for each type of page. These template files consist mostly of pure HTML; the only PHP code they contain is there to output the values of PHP variables created by the controller. The code in these files is kept very simple, so that they can be handed off to designers who may be unfamiliar with PHP at all. Also, using separate files makes it easy to generate several different types of page (that is, serveral different template files) from a single controller.

All the little changes in approach like this one are what really makes me proud of Build Your Own Database Driven Web Site Using PHP & MySQL, 4th Edition. I used to describe the third edition of this book as giving beginners "just enough rope to hang themselves with."

With the fourth edition, beginners can breeze past the self-strangulation stage — hopefully straight into a well-paying career as a PHP developer!

I bet you’re wondering where the code is, right? To see how the “pretty URL” technique described above looks in code, be sure to check out Chapter 3 when we publish it on Thursday. Or if you’re unable to wait, grab all four chapters in PDF format today — free of charge.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Genjutsushi

    And I was wondering whether it’d be worth getting the 4th edition, having bought the 3rd and not having had chance to read it yet.

    I’m sold.

  • krdr

    It would be nice if Sitepoint make supplement to 4th edition for 3rd edition owners. I would pay 5$ for that.

  • http://www.sitepoint.com/ Kevin Yank

    krdr, there isn’t a single page in the book that hasn’t been extensively modified or re-written from scratch, and all but one or two examples have dramatically changed. A supplement simply isn’t possible.

    That said, we are offering a generous discount on the 4th edition for 3rd edition owners. If you haven’t yet received an email about it, drop us a line and we’ll hook you up.

  • Martin F

    This feels a bit like bastardizing a proper setup. I’d make sure you _carefully_ explain that this just mimics how it would look, and it’s not how it’s actually done, otherwise we’ll just see this in production when the fledgling programmers start publishing stuff; can you imagine the amount of face palming required then?

    I honestly don’t see why examples of how to configure this in Apache via pass thru wouldn’t have been ten times better. That way you also get to promote single point of entrance, you don’t need to duplicate lots of code and best of all you get to actually have URL arguments properly instead if /your/pretty/url/?which=is&not=prettyreally

    I realize this book is aimed at beginners, but that doesn’t mean you have to dumb down everything to a level where it will just confuse more than help.

  • Jory Geerts

    Is the following really that hard? You won’t have to explain in great detail how it works and its easy enough to explain what it does.

    <IfModule mod_rewrite.c>
    	RewriteEngine On
    	RewriteCond %{REQUEST_FILENAME} !-f
    	RewriteCond %{REQUEST_FILENAME} !-d
    	RewriteRule (.*) index.php [QSA] [L]
    </IfModule>
    $requestData = explode( $_SERVER['REQUEST_URI'] );
  • http://www.northwinddesign.com allspiritseve

    What happened to mod_rewrite?

  • http://bubbabelly.blogspot.com BubbaBelly

    I think the multiple folder approach is messy and ameteur. We don’t live in 1996 anymore! What about .htaccess files and utilities like ISAPI Rewrite? Also, why not follow the example of techniques of the Zend Framework? They did create PHP.

  • http://www.lunadesign.org awasson

    Right on Kevin!

    I read your book ages ago… It must have been when it first came out because it was in article format on the site and I printed out every page… I still have it in my bookshelf full of highlighter and postit notes : )

    It sounds like the new book is introducing the reader to design patterns or at least agile development practices. I’ve got the first 4 chapters and may just buy the book to go with the rest of my SP arsenal. The original was a great read so I expect the new one will be even better.

    Cheers,
    Andrew

  • arts-multimedia

    I’ve got those early chapters too, printed from the site. They were a great help for me setting up a test server on my computer and do my first php project. Tha

  • arts-multimedia

    I actually didn’t know that showing .php is a problem, actually. I also notice that sitepoint has many php urls, so in that respect I do not understand why you say that developers using the regular method would be out of a job. :-)
    That said, in the meantime I do not develop in php myself anymore, but rather leave it to a specialist. After all, design is not the same as programming or scripting.
    In any case, I’m quite sure your new book will be worthwhile.

  • Dorsey

    Not everyone has access to their host’s Apache configuration, so it doesn’t matter how easy this would be, those approaches are non-starters.

    I’m assuming that the concept of modular programming and reusable code aren’t new concepts for seasoned pros, but I do think that those are concepts not immediately obvious to newbies and/or casual programmers. I lump graphic designers into the latter category. Although I’ve seen some graphic types who can grasp engineering principals, the creative side is the wrong side of the brain for serious software engineering. Yes, I know that will be offensive to some, but before you knock me down to size, consider your attitude towards engineers who try to draw things and make pretty pages.

  • http://www.northwinddesign.com allspiritseve

    @Dorsey most should be able to use .htaccess files though. I would not use any host that didn’t allow them. mod_rewrite is the de facto standard for clean urls.

  • http://www.evanbot.com ETbyrne

    Old news, I wrote a tutorial on fancy urls in PHP without mod_rewrite way back in November 2008… Here’s my shameless plug: link

  • http://www.lunadesign.org awasson

    Dorsey is right. mod_rewrite isn’t always available and when it isn’t, you need an alternative. I wish I could pick and choose where all of my sites are hosted but there are a lot of them and I don’t determine where they all reside. Some sites are hosted by clients in-house on IIS boxes with PHP in CGI mode and there is no mod_rewrite available if it’s on IIS unless you purchase a ISAPI_Rewrite module and configure it but that isn’t always possible.

  • the ImageSmith

    I’m with BubbaBelly.
    Why not get some basics of MVC theory going rather than tout a system that will produce a rubbish project layout and mean that new programmer cannot even get a job let alone lose one?
    There are plenty of MVC frameworks out there that eeven a novice can work with – Zend, Codeigniter, etc.
    At the end of the day, good on you for the effort in writing the book. Perhaps you should bend your literary efforts in this direction next time Kevin and help some noobies get really useful knowledge (ie what industry is currently using).

  • Anonymous

    For those people rubbishing the content of the book, maybe you should look again at the book title. It’s about php and mysql end of story. It’s not about developing in current code frameworks, nor is it about how to configure your web server. I would be surprised if those topics aren’t mentioned in passing though. This is a book about learning the fundamentals of using php with mysql to develop database driven websites. Kudos to Kevin for keeping the book on topic.

  • Justen

    Honestly? Sounds messy, distracting, and obtuse. Use mod_rewrite to rewrite directories into query strings – simple problem, simple answer. In your system, a file structure change spells disaster and there’s tons and tons of code duplication going on. Whether you write procedural or object oriented code, this is a terrible and pointless mess when the equivalent solution in mod_rewrite can be copy-pasted off of numerous examples on the web.

    If for some odd reason your server does not support mod_rewrite and you cannot install it or have it installed, GET ANOTHER SERVER. The medium-long term cost of maintaining this mess is much higher than a simple server swap for any project where this would be a possible solution in the first place.

  • arts-multimedia

    I agree with Dorsey:

    Although I’ve seen some graphic types who can grasp engineering principals, the creative side is the wrong side of the brain for serious software engineering.

    At best, a graphic designer can be a good amateur in programming. It took me a couple of years to accept that and give the programming to someone who doesn’t do anything else. However, it is important for a graphic designer to have an understanding of programming so that he/she knows what can be done and what not.
    Thereofroe, a graphic designer without any knowledge of programming is a

  • arts-multimedia

    always a bit handicapped when talking with clinets(I wanted to finish, sorry about that).

  • http://www.sitepoint.com/ Kevin Yank

    Good debate so far. Obviously, I don’t believe full-on OOP theory or Apache server configuration belongs in an absolute beginner’s PHP book, but this approach lays the groundwork for learning MVC frameworks by dividing the code into a model (shared include files), the view (template files), and the controller (index.php).

    I think you’ll agree that if someone who has never written any type of computer program before can pick up a 400 page book and learn to write a simple, secure PHP application structured in this way, that’s a pretty solid achievement.

  • langsor

    I don’t care what they say about you Kevin, I think you do good work. ;-)

    I too jumped to the mod_rewrite option and also saw the likelihood of code duplication (although not necessarily depending on dependency structures), but what I know is true is that there is almost always more than just one way to peel an orange (or some such cliche) and you’re not going to learn all of them in a one-off scenario. The templates and separation is a good place to start of beginners and will get them off bad habits before they ever start.

    For you folks that say designers and programmers don’t come in the same package, think again, it may be rare, but I know it’s possible. Now maybe a jack of all trades will be less a master at all, but can still be a master.

    Thanks for letting me have my word.

  • http://www.lunadesign.org awasson

    @Anonymous: For those people rubbishing the content of the book, maybe you should look again at the book title. It’s about php and mysql end of story. It’s not about developing in current code frameworks, nor is it about how to configure your web server. I would be surprised if those topics aren’t mentioned in passing though. This is a book about learning the fundamentals of using php with mysql to develop database driven websites. Kudos to Kevin for keeping the book on topic.

    Thanks for posting that. I certainly couldn’t have put it any better.

  • http://bubbabelly.blogspot.com BubbaBelly

    I have the first edition of this book. It was great at the time, for the time. I was just beginning with PHP and MySQL, and in many regards so was PHP and MySQL as a combined solution. But its been what, 6 or 7 years?

    I think an introductory book should definitely cover the ideas of .htaccess, mod_rewrite, and MVC architectures, etc. Anyone looking into the subject is not interested in building a simple “mom and pop” sort of website. I understand that the book is not intended to go in-depth on these issues, but I think they should be presented as, “this is the way it’s being done now”.

    I can’t tell you how many times, I’ve searched for something or read something and only gotten half the answer. You then go and do it and learn the other half. Which is great for enhancing the understanding of things, but I also think it would be incredibly helpful if the popular and credible resources told more of story, etc. I don’t mean to imply the book by Kevin is lacking is such regard, these are just some thoughts.

    However, I think sometimes a disservice is done to “beginners” or the development community by dumbing it down too much. The more information, the better.

  • http://www.lunadesign.org awasson

    I’m afraid I have to disagree with the premise that a beginner’s book should contain all of the stuff that we’ve been learning and refining over the last decade. Sure design patterns is important as is htaccess & the various apache modules but you have to keep in mind that these are beginners reading the book.

    Most people begin programming by writing a “hello world” program. After that it takes quite some time to move on to the more advanced topics like dealing with datasets, paging results, optimizing the database structure, manipulating data with the help of arrays, using CSS to style the presentation, etc… Too much information would likely stall the beginner out.

  • arts-multimedia

    I agree with BubbaBelly. A beginner expects to be able to write a full application after reading a book. and that it should include a couple of samles with .htAccess, mod_rewrite and such. Beginners are not necessarily fragile creatures breaking to pieces when they see some advanced code.:-)

    That the book should cover MVC architecture might be a bit too much, although a general idea of the concept would be a good idea. After all, not everyone will want to build large systems, and those who want, could buy a specialized book on MVC frameworks. There are many books that cover this subject.

  • gtipete

    If you are worried that beginners are not ready for the complexity involved in creating clean urls, then let them have their fun with query strings.
    I think that if the whole concept behind clean urls was broken down into ‘building blocks’ and the code was explained in simple terms most beginners would get their head around it.