【问题标题】:Custom URL for user profile page用户个人资料页面的自定义 URL
【发布时间】:2017-12-02 12:24:37
【问题描述】:

我有一个基本的 PHP 脚本,它以简单的格式显示来自 MySQL 数据库的用户配置文件信息。目前,要查看个人资料,请输入以下链接:

https://xxx.xxx.com/profile.php?id=XXX

不过,我想要的是类似于 Twitter 的东西,其中的 URL 看起来更像:

https://xxx.xxx.com/profile/UserName

我已经阅读了friendly urls for users profile?,但建议使用:

https://xxx.xxx.com/profile.php?username=UserName

...这不是我想要的。有什么办法可以做到这一点?谢谢。

【问题讨论】:

标签: php mysql url


【解决方案1】:

试试下面的代码 您的 .htaccess 文件将包含此代码

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/$    index.php    [L]

RewriteRule ^profile/([A-Za-z0-9-]+)/?$    profile.php?username=$1    [NC,L]    
RewriteRule ^([^\.]+)$ $1.php [NC,L]

注意:从您提供链接的位置只需将链接作为 http://example.com/profile/username

如果您的用户名包含空格、字符串,则 url 将不干净,因此请确保用户名不得包含任何特殊字符或空格

使用下面的函数删除和获取干净的字符串

function to_prety_url($str)
{
    if($str !== mb_convert_encoding( mb_convert_encoding($str, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') )
        $str = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    $str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace('`&([a-z]{1,2})(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);`i', '\1', $str);
    $str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    $str = preg_replace(array('`[^a-z0-9]`i','`[-]+`'), '-', $str);
    $str = strtolower( trim($str, '-') );
    return $str;
}

【讨论】:

    【解决方案2】:

    感谢“daker”的回复。要回答我自己的问题,我需要使用 URL 重写。对于寻找如何做到这一点的其他人,我建议查看https://www.addedbytes.com/blog/url-rewriting-for-beginners,它提供了一个全面的初学者友好指南。另外,我在 Google 上搜索了“重写生成器”,并使用了一个生成对我有用的重写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 2023-03-23
      • 2018-01-26
      相关资源
      最近更新 更多