dongxun1244 2013-05-05 20:43
浏览 79
已采纳

使用PHP重写URL

I have a URL that looks like:

url.com/picture.php?id=51

How would I go about converting that URL to:

picture.php/Some-text-goes-here/51

I think WordPress does the same.

How do I go about making friendly URLs in PHP?

  • 写回答

5条回答 默认 最新

  • dpgu5074 2013-05-05 20:53
    关注

    You can essentially do this 2 ways:

    The .htaccess route with mod_rewrite

    Add a file called .htaccess in your root folder, and add something like this:

    RewriteEngine on
    RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
    

    This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

    The PHP route

    Put the following in your .htaccess instead: (note the leading slash)

    FallbackResource /index.php
    

    This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

    $path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
    $elements = explode('/', $path);                // Split path on slashes
    if(empty($elements[0])) {                       // No path elements means home
        ShowHomepage();
    } else switch(array_shift($elements))             // Pop off first item and switch
    {
        case 'Some-text-goes-here':
            ShowPicture($elements); // passes rest of parameters to internal function
            break;
        case 'more':
            ...
        default:
            header('HTTP/1.1 404 Not Found');
            Show404Error();
    }
    

    This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算