URL Routing with PHP

Josh Sherman
2 min read
Software Development PHP

I’ve been taking a lot of programming tests / challenges recently as I was in the market for a new [and hopefully exciting] opportunity to spend my time on. Because of this, I am full of new blog post ideas based on the questions / challenges asked. This week I’m going to discuss how to handle URL routing with PHP.

There is one major assumption here, it’s that all of your URIs route directly to a single script, for instance index.php. I feel like setting this up is a bit out of scope as it’s a bit different depending on the web server you’re running. If there’s enough feedback that this should be included, I’ll go ahead and get it added, but until then, I’ll assume you can handle that part.

The next (not so major) assumption is that your URI structure will lend itself to a specific class structure. For the sake of example, a URI like /user/edit will call the edit() method on the User class. We will be sure to sanity check the existance of both while exploiting the fact that you can instantiate classes and request methods stored in strings.

$uri = explode('/', strtolower(substr($_SERVER['REQUEST_URI'], 1)));

$class  = ucfirst($uri[0]);
$method = $uri[1];

	if (class_exists($class))
		$object = new $class();

		if (method_exists($object, $method))
			throw new Exception('Requested method does not exist.');
		throw new Exception('Requested class does not exist.');
catch (Exception $e)

This is obviously a very rudimentary example with less than ideal error handling. You can easily route the user to a URI for the error page or even push a 404 error to the browser. Another short coming is the fact that we are only handling URIs with 2 parts /first/second, but you can set up handling for single part or 3+ part URIs if so desired. A lot of it depends on your application needs and how you want to set things up.

For anyone state side, I hope you had a great Memorial Day weekend! And for any service men & women turned coders, I thank you.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles