0

I'm having a trouble while I'm trying to read the full path of my website address, using .htaccess friendly URL. The point is this:

I have an htaccess, which has this:

RewriteRule ^(.*)$ index.php?loadpage=$1 [L]

What this code actually does, is when I enter to mywebiste.com/params, it's interpreted by htaccess as ?loadpage=params. If I have more params, it's gonna be read like this: ?loadpage=params/param1/1.

So: http://mywebsite.com/params/param1/1 = http://mywebsite.com/index.php?loadpage=params/param1/1.

The way I read these params, is using a simply explode:

$params = explode("/", $_GET['loadpage']);

So it's simply now, because I read it like this:

$params[0] = "params";
$params[1] = "param1";
$params[2] = "1";

I mean, if I want to catch some value from URL, i MUST KNOW where is it placed, because if not, the array will be empty.

Even at this point, I'm asking myself if this is actually correct. This isn't hard as it seems, it's easy to manage those arrays if you know its position everytime.

My big trouble comes when I need to work with many address, many parameters. It's hard to control them, because the difference between $GET and this kind of count that I'm having, is that I know the KEY and VALUE of GET. But in the way I'm using, I only get the VALUE, so I must calculate the key, assuming its position and some other vars.

Hope you guys help, I'm going crazy with this. Thanks.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183

1 Answers1

1

For example:

<?php
   // http://domain.com/key1/value1/key2/value2/key3
   $query = explode('/',trim($_SERVER['QUERY_STRING'],'/'));
   $param_pairs = array_chunk($query,2);
   foreach($param_pairs as $param_pair){
      if(count($param_pair) == 2)
         $query_params[$param_pair[0]] = $param_pair[1];
      else
         $query_params[$param_pair[0]] = 1;
   }
?>

This will return array:

array(key1 => value1, key2 => value2, key3 => 1);

So now you can access params by:

$query_params[`key`]
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
  • I also thought that. So you think this is the best solution then? :) what do you think about the count the items according to array, you think it's a good method? Thankd – Jack Johnson May 26 '14 at 17:25
  • I was using this method in few bigger projects and never had any problems. Is it the best way? Probably one of the best if you are looking for simple solution with good results. I am limiting query to 20 chunks, and if its bigger, I send `HTTP/1.1 503 Bad request` header, but it is because my function is much bigger (it looks for files first in application tree to include and all rest assigns as params) ... it's pretty universal. – Flash Thunder May 26 '14 at 17:49