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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失