In PHP I am trying to write an article section. A totally fictitious article URL would be in the format:
http://www.example.com/articles/fix/appliances/how-to-repair-a-microwave/
What I am getting hung up on is how to make it so that I can make each part of the url properly show the data that is required and if they add anything thats not in the right format, it state page does not exist.
For example, if a visitor went to http://www.example.com/articles/ it would show a listing of all the articles. If they went to http://www.example.com/articles/fix/ it would show only articles under the fix category. If they went to http://www.example.com/articles/fix/appliances/ it would show only the articles under the fix appliances category, etc.
I can explode the $_SERVER[‘REQUEST_URI’] to evaluate which function in the PHP code I should perform. For example show a feed or show a category.
$match = explode('/', $_SERVER['REQUEST_URI']);
switch($match[2]) {
case 'feed':
show_rss();
break;
default:
show_category();
break;
}
My confusion, though, is how to differentiate between a category and an actual article. In the show_category() function, I could take the last part of the url path and check a database to see if an article exists using that path. If it does, show the article, else assume its a category. I am not sure, though, that this is the most efficient way of doing it.
I’m going to assume that you’re appropriately accessing your script in such a way that the script is running from a single generic location, but the best way to access the data you want is from
$_SERVER['REQUEST_URI']. Personally I’d use mod_rewrite, but that’s a separate matter from your question.Since you’re providing the links to these pages, you could append an extension on your article key:
http://www.example.com/articles/fix/appliances/how-to-repair-a-microwave.article/If a dash will always be present in the article key but never in a category key, you could preg_match for a dash.
Otherwise, you’re pretty much set to check each key against the database. What I’d do instead, though, is run each entry against the category database. Presumably if it’s an article key, it won’t match against the category table, and then you can try to match it against the article table. That will be more efficient than trying to match every time against the article table.
Edit: it’s actually more appropriate to say, it’s more efficient to check against the table that will be used most often. If people will be hitting the category navigation pages more often, then you should attempt to match the last key first against the categories table. If people will be hitting the article pages more often, then you should check against the article page first. This is just a matter of watching your server logs and reacting appropriately.