【问题标题】:How to create friendly URL in php?如何在 php 中创建友好的 URL?
【发布时间】:2022-01-02 12:14:12
【问题描述】:

通常,显示某些个人资料页面的做法或非常古老的方式是这样的:

www.domain.com/profile.php?u=12345

u=12345 是用户 ID。

近年来,我发现一些网站的网址非常好,例如:

www.domain.com/profile/12345

我如何在 PHP 中做到这一点?

就像一个疯狂的猜测,它与.htaccess 文件有关吗?你能给我更多关于如何编写.htaccess文件的提示或一些示例代码吗?

【问题讨论】:

标签: php url friendly-url


【解决方案1】:

执行此操作的简单方法。试试这个代码。将代码放入您的 htaccess 文件中:

Options +FollowSymLinks

RewriteEngine on

RewriteRule profile/(.*)/ profile.php?u=$1

RewriteRule profile/(.*) profile.php?u=$1   

它将创建这种类型的漂亮 URL:

http://www.domain.com/profile/12345/

更多htaccess漂亮网址:http://www.webconfs.com/url-rewriting-tool.php

【讨论】:

  • 简洁优雅。为我工作。
【解决方案2】:

根据this article,您需要一个看起来像这样的mod_rewrite(放置在.htaccess 文件中)规则:

RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1

这会映射来自

的请求
/news.php?news_id=63

/news/63.html

另一种可能性是使用forcetype 来执行此操作,这会迫使任何东西沿着特定路径使用 php 来评估内容。因此,在您的 .htaccess 文件中,输入以下内容:

<Files news>
    ForceType application/x-httpd-php
</Files>

然后index.php可以根据$_SERVER['PATH_INFO']变量采取行动:

<?php
    echo $_SERVER['PATH_INFO'];
    // outputs '/63.html'
?>

【讨论】:

  • 一个很棒的 mod_rewrite 资源:addedbytes.com/apache/mod_rewrite-cheat-sheet
  • 另一个选项,如果你想完全用 PHP 重写你的 URL,是设置重写规则来将所有请求定向到一个脚本。这样做的一大优势是,您可以将代码存储在 Apache 无法访问的区域,并且只有您的 URL 调度脚本需要是 Apache 可访问的。例如: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule 。 dispatch.php 这类似于你的 forcetype 示例。
  • 关于 Phpriot 的文章已被删除,read it here。这是非常好的作品。
  • 如果 id=1 和 post_name="red post" ,那么是否有可能创建像 example.com/red-post.php 这样的 url。目前我正在创建像 example.com/post/?id=1 这样的 url。即如何通过帖子名称制作slug(url)
  • James SocolChad Birch发布的链接失效了。
【解决方案3】:

我尝试在下面的示例中逐步解释这个问题。

0) 问题

我试着这样问你:

我想打开像 facebook 个人资料 www.facebook.com/kaila.piyush 这样的页面

它从 url 获取 id 并将其解析为 profile.php 文件并从数据库返回 fetch 数据并将用户显示到他的个人资料

通常当我们开发任何网站时,它的链接看起来像 www.website.com/profile.php?id=用户名 example.com/weblog/index.php?y=2000&m=11&d=23&id=5678

现在我们更新新样式而不是重写我们使用 www.website.com/username 或 example.com/weblog/2000/11/23/5678 作为永久链接

http://example.com/profile/userid (get a profile by the ID) 
http://example.com/profile/username (get a profile by the username) 
http://example.com/myprofile (get the profile of the currently logged-in user)

1) .htaccess

在根文件夹中创建一个 .htaccess 文件或更新现有文件:

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

那有什么作用?

如果请求是针对真实目录或文件(存在于服务器上的),则不提供 index.php,否则每个 url 都会重定向到 index.php。

2) index.php

现在,我们想知道要触发什么动作,所以我们需要读取 URL:

在 index.php 中:

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);

for ($i= 0; $i < sizeof($scriptName); $i++)
{
    if ($requestURI[$i] == $scriptName[$i])
    {
        unset($requestURI[$i]);
    }
}

$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
switch($command[0])
{
    case ‘profile’ :
        // We run the profile function from the profile.php file.
        profile($command([1]);
        break;
    case ‘myprofile’ :
        // We run the myProfile function from the profile.php file.
        myProfile();
        break;
    default:
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";
        break;
}

2) profile.php

现在在 profile.php 文件中,我们应该有这样的内容:

// profile.php

function profile($chars)
{
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........
    }

    // Render your view with the $user variable
    // .........
}

function myProfile()
{
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :
    profile($id);
}

【讨论】:

  • 感谢详细的帖子,我一直想学习,像 wordpress 这样的网站如何生成漂亮的 url,并且无需每次都编辑 htaccess 文件即可访问它们,谢谢
  • 这正是我想要的。
  • 你如何处理#anchors?
【解决方案4】:

有很多不同的方法可以做到这一点。一种方法是使用前面提到的 RewriteRule 技术来屏蔽查询字符串值。

我真正喜欢的一种方式是,如果您使用front controller 模式,您还可以使用http://yoursite.com/index.php/path/to/your/page/here 之类的网址并解析$_SERVER['REQUEST_URI'] 的值。

您可以使用以下代码轻松提取 /path/to/your/page/here 位:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

从那里,您可以随心所欲地解析它,但为了皮特,请确保您对其进行消毒;)

【讨论】:

    【解决方案5】:

    ModRewrite 不是唯一的答案。您还可以在 .htaccess 中使用 Options +MultiViews,然后检查 $_SERVER REQUEST_URI 以查找 URL 中的所有内容。

    【讨论】:

    • 是的,但是 MultiViews 很讨厌......我想说它对于这种用法来说太笼统了。
    【解决方案6】:

    我最近在一个可以很好地满足我的需求的应用程序中使用了以下内容。

    .htaccess

    <IfModule mod_rewrite.c>
    # enable rewrite engine
    RewriteEngine On
    
    # if requested url does not exist pass it as path info to index.php
    RewriteRule ^$ index.php?/ [QSA,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) index.php?/$1 [QSA,L]
    </IfModule>
    

    index.php

    foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
    {
        // Figure out what you want to do with the URL parts.
    }
    

    【讨论】:

      【解决方案7】:

      您似乎在谈论 RESTful Web 服务。

      http://en.wikipedia.org/wiki/Representational_State_Transfer

      .htaccess 文件确实重写了所有 URI 以指向一个控制器,但这比您现在想要的更详细。你可能想看看Recess

      这是一个 RESTful 框架,全部用 PHP 编写

      【讨论】:

      • 从技术上讲,我想你是对的,但除非 OP 已经对 REST 想法有经验,否则即使阅读 Wikipedia 文章也比问题需要付出的努力要多得多。在这种情况下调用整个编程范式是多余的。
      • 真的吗?我不认为他的问题完全是“我如何制作 profile.php?u=12345 goto /profile/12345”,我将其解释为整体“这是如何在生产环境中完成的?”。我认为知道那里有一个范例是有益的,并且当有解决该问题的正确方法时,没有一个充满重定向的 .htaccess 文件。
      【解决方案8】:

      它实际上不是 PHP,它是使用 mod_rewrite 的 apache。发生的情况是该人请求链接 www.example.com/profile/12345,然后 apache 使用重写规则将其切碎,使其看起来像这样,www.example.com/profile.php?u=12345,到服务器。你可以在这里找到更多:Rewrite Guide

      【讨论】:

        猜你喜欢
        • 2016-06-02
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        相关资源
        最近更新 更多