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条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)