dongzi3805
dongzi3805
2012-01-23 12:15
浏览 14
已采纳

如何从网址获取价值?

If I have url like this: www.example.com/product/yellow-bed is it possible to retrieve product name from url? For example, if url would be like www.example.com?page=product&product_name=yellow_bed I would use:

$product = $_GET['page'];
$product_name = $_GET['product_name'];

But how to get it from www.example.com/product/yellow-bed ?

图片转代码服务由CSDN问答提供 功能建议

如果我有这样的网址: www.example.com/product/yellow-bed 是否可以从网址中检索产品名称? 例如,如果网址与 www.example.com?page=product&product_name=yellow_bed 一样,我会使用:

  $ product = $ _GET ['page']; 
 $ product_name = $ _GET ['product_name']; 
   
 
 

但是 如何从 www.example.com/product/yellow-bed 获取它?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • douhuan1257
    douhuan1257 2012-01-23 12:22
    已采纳

    Get the URI by "$_SERVER["REQUEST_URI"]". Convert the string into an array with explode:

    $uri = 'www.google.com/product/yellow-bed' //uri = $_SERVER["REQUEST_URI"]
    $uriArray = explode('/', $uri);
    $product = $urlArray[1];
    $product_name = $urlArray[2];
    

    0 = www.google.com, 1 = product, 2 = yellow-bed

    PHP manual: array explode ( string $delimiter , string $string [, int $limit ] ).

    点赞 评论
  • doudengshen5591
    doudengshen5591 2012-01-23 12:19

    Some php frameworks (like CodeIgniter) has already this function implemented. Never the less you can have a look here: http://erunways.com/simple-php-get-uri-or-segment-element/ , and that should solve your problem.

    点赞 评论
  • dtiopy6088
    dtiopy6088 2012-01-23 12:19

    You could fetch the complete URI with $_SERVER['QUERY_STRING'] and then split it apart. Or you work with an .htaccess and internally rewrite the url.

    点赞 评论
  • dongmeng9048
    dongmeng9048 2012-01-23 12:19

    Try $_SERVER[ 'PATH_INFO' ] or $_SERVER[ 'REQUEST_URI' ].

    点赞 评论
  • douzhu6149
    douzhu6149 2012-01-23 12:19

    You should have a look at $_SERVER['REQUEST_URI']. This will be /product/yellow-bed in your example.

    You can then use strrpos(), explode() orpreg_match()` (or other string manipulation functions) to extract what you want.

    点赞 评论
  • dongzanghua8422
    dongzanghua8422 2012-01-23 12:22

    you can use the following function to retrive current url:

    <?php
    function curPageURL() {
     $pageURL = 'http';
     if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
      $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }
     return $pageURL;
    }
    ?>
    

    now you can take url and parse its elements using parse_url : http://php.net/manual/en/function.parse-url.php

    点赞 评论

相关推荐