douwen3362 2014-11-04 15:22
浏览 38
已采纳

如何为urps编写.htaccess for twitter API

I'd like to write a proper .htaccess rule and PHP code to parse url like this one : https://myapi.com/1.1/users/search.json?q=abc&page=1&count=3

Here's what I found so far:

RewriteRule ^([a-zA-Z_-])\.(xml|json)$   index.php?url=$1&format=$2

And my PHP code looks like

$requestParts = explode('/', $_GET['url']);
$contentType = $_GET['type'];
//$params = ... //Here's where I'm lost

How can I get the optional part with the RewriteRule and PHP code ?

  • 写回答

1条回答 默认 最新

  • duanjianxiu9400 2014-11-04 15:37
    关注

    My suggestion would be to use a very simple rewrite to a front controller (like index.php) and then use code in that file to evaluate the requested route.

    RewriteRule ^index\.php$   index.php [L,QSA]
    

    In your api example you would then have paremeters q,page,count available in $_GET due to the QSA (query string append) flag on the rewrite rule.

    This leaves it up to you to interpret the rest of the URI.

    You can do that rather simply using simple string manipulation techniques.

    // discard query string after trimming leftmost '/' from URI
    $uri_parts = explode('?', ltrim($_SERVER['REQUEST_URI'], '/'));
    $uri_base = $uri_parts[0];
    // get routing information from URI
    $route_parts = explode('/', $uri_base);
    $api_version = $route_parts[0];
    $controller = $route_parts[1];
    $action_parts = explode('.',$route_parts[2]);
    $action = $action_parts[0];
    $format = $action_parts[1];
    // your parameters would be in $_GET['q'], $_GET['page'], etc. 
    

    You might consider Googling PHP URL routing to get more examples of how to set up a proper router, as this was just a very basic example and does not include any sort of validation or handling of more complex routes.

    The benefit of this approach is that it keeps your routing logic all in PHP rather than split between Apache server config and PHP. If you need to make routing changes, you do it in PHP only. This also prevents mixing of routing information with actual parameter information within $_GET as would happen with your proposed rewrite.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)