00 Votes

HTACCESS: Parts of URL as Parameter - Explode at Slash

Question by Compi | 2017-09-27 at 20:02

I would like to use the parts between the slashes of my URLs as single parameters in PHP. Therefore, I am searching for a fitting .htaccess routine to implement that.

For example, when the following URL is called

example.com/param1/param2/param3

I would like to get the three variables $param1, $param2 and $param3 in my PHP script independent from what text param1, param2 or param3 in the URL have:

$param1   // 'param1'
$param2   // 'param2'
$param3   // 'param3'

How is that possible? Do you have any tips or advice for me? I need something like a so to say explode() function you know from PHP but for HTACCESS.

ReplyPositiveNegativeDateVotes
0Best Answer0 Votes

The easiest way would be to just use the explode-function of PHP.

An implementation could look like that:

$url = $_SERVER['HTTP_REQUEST_URI'];
$parts = explode('/', $s);

$param1 = $parts[1];
$param2 = $parts[2];
$param3 = $parts[3];

With $_SERVER['HTTP_REQUEST_URI'] you can read out the complete URI which would be "/param1/param2/param3" in your case. After that, we are just using PHP's explode() for dividing the URI into its parts and to store them in your parameters.

At this point, it is important not to start the index at 0 but at 1, because the URI is starting with / resulting in an empty $parts[0].
2017-09-28 at 08:42

ReplyPositive Negative
00 Votes

Of course, I do not want to withhold the implementation with an HTACCESS-Rewrite. In this case, the Rewrite Rule can look like that, for example:

RewriteRule ^([^/]+)/([^/]+)/(.+)$ index.php?param1=$1&param2=$2&param3=$3

With [^/]+ we are matching all what is no Slash. In PHP, we can then access the individual parts with $_GET[param1], $_GET[param2] and $_GET[param3].

Of course, this is only working in case your URL is exactly consisting of three parts. If not, you should better take the PHP-explode-solution from my other post to make it not too complicated. However, if you only have URLs consisting of a limited number of parts, for example only 1, 2 or 3 parts, you can also make a rule for each analogous my example above.
2017-09-28 at 19:26

ReplyPositive Negative
Reply

Related Topics

HTACCESS: Simplify URL

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.