dongqiao1964 2014-05-26 16:53
浏览 75
已采纳

如何在PHP中正确读取.htaccess GET的完整路径?

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.

  • 写回答

1条回答 默认 最新

  • dtuct88226 2014-05-26 17:06
    关注

    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`]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器