【发布时间】:2016-02-06 16:52:32
【问题描述】:
我真的很难理解如何使用重写规则修改 URL。我看过以下链接:Directly adding username to URL PHP - 但以下知识似乎对我不起作用。
我需要 url 说例如。
http://localhost/profile_page/Freddy
而不是:
http://localhost/profile_page.php
.htaccess(位于默认 Wamp 文件夹中,C:\wamp\www)
RewriteEngine On
RewriteBase /wamp/www/
RewriteRule ^/?$ profile_page.php
RewriteRule ^/me?$ profile_page.php
RewriteRule ^/profile_page.php/([a-zA-Z0-9_\-]+)/?$ profile_page.php?u=$1
RewriteRule ^/profile/([a-zA-Z0-9_\-]+)/?$ profile_page.php?u=$1
RewriteRule ^/([a-zA-Z0-9_\-]+)/?$ profile_page.php?u=$1
我有以下问题:
1. 有了上面的规则,虽然我在这方面的知识有限,但我希望它能将http://localhost/profile_page.php的url转换为显示登录用户的名称,即http://localhost/profile_page/Freddy .
登录用户的详细信息可以从会话变量$username 或变量$user 中获取,该变量获取url 中“u=”后的用户名(见下文)。但是,该 url 不显示登录用户的名称,它只是显示 http://localhost/profile_page.php,如果以 Freddy 身份登录,我希望它显示 http://localhost/profile_page/Freddy。
<?php
$user = "";
if (isset($_GET['u'])) {
$user = ($_GET['u']);
if (ctype_alnum($user)) { //check if the user exists
$check = mysqli_query($connect, "SELECT * FROM users WHERE username='$user'");
if (mysqli_num_rows($check) === 1) {
$get = mysqli_fetch_assoc($check);
$user = $get['username'];
$fname = $get['first_name'];
echo "<h2>Profile page for: $user</h2>";
} else { // refresh page
echo "<meta http-equiv=\"refresh\" content=\"0; url=http://localhost/index.php\">";
exit();
}
}
}
?>
2. 如果在 URL 中输入 http://localhost/profile_page.php?u=Fred,它会回显它在 Fred 的页面上,但会显示登录用户的个人资料页面,因此它会显示帖子和信息网址中指定的 Freddy,而不是 Fred。
【问题讨论】:
-
@anubhava -
RewriteBase不正确吗?我知道RewriteBase为您的重写提供了基础,但假设这意味着根文件夹。 -
@anubhava - 对,我想我现在明白了。谢谢,我已将 RewriteBase 更改为
RewriteBase /。但同样的问题仍然存在,该 URL 不显示用户名或允许我通过在 URL 中绑定他们的用户名来跳转到另一个用户的个人资料页面。