I am currently working on a blog where I would like to create links to my individual articles in the following form:
http://www.mysite.com/health/2013/08/25/some-random-title
------ -----------------
| |
category title
However I have no idea how to achieve this.
I have found something that would give me the URI.
$uri = $_SERVER["REQUEST_URI"];
I would then go ahead and extract the needed parts and make requests against the database. This may seem a very very dumb question, but I do not know how to look this up on google (I tried...) but how exactly am I going to handle the link ?
I try to explain it step-by-step:
User clicks on article title -> the page reloads with new uri --> Where am I supposed to handle this new uri and how ? If the request path looked like this:
index.php?title=some-random-article-title
I would do it in the index.php and read the $_GET array and process it accordingly. But how do I do it with the proposed structure at the beginning of this question ?
You will need a few things:
Setup an .htaccess to redirect all request to your main file which will handle all that, something like:
The above will redirect all request of non-existent files and folder to your
index.php
Now you want to handle the URL Path so you can use the PHP variable
$_SERVER['REQUEST_URI']
as you have mentioned.From there is pretty much parse the result of it to extract the information you want, you could use one of the functions
parse_url
orpathinfo
orexplode
, to do so.Using
parse_url
which is probably the most indicated way of doing this:Output:
So
parse_url
can easily break down the current URL as you can see.For example using
pathinfo
:$path_parts['dirname']
would return/health/2013/08/25/
$path_parts['basename']
would returnsome-random-title
and if it had an extension it would returnsome-random-title.html
$path_parts['extension']
would return empty and if it had an extension it would return.html
$path_parts['filename']
would returnsome-random-title
and if it had an extension it would returnsome-random-title.html
Using explode something like this:
Output:
Of course these are just examples of how you could read it.
You could also use .htaccess to make specific rules instead of handling everything from one file, for example:
Basically the above would break down the URL path and internally redirect it to your file blog.php with the proper parameters, so using your URL sample it would redirect to:
However on the client browser the URL would remain the same:
There are also other functions that might come handy into this for example
parse_url
,pathinfo
like I have mentioned early, server variables, etc...