在这个链接上,我在谷歌搜索这个问题后写了,我找到了解决方案
点击这里查看本教程,然后阅读以下步骤
0) 问题
我试着这样问你:
我想打开像 facebook 个人资料 www.facebook.com/kaila.piyush 这样的页面
它从 url 获取 id 并将其解析为 profile.php 文件并从数据库返回 fetch 数据并将用户显示到他的个人资料
通常,当我们开发任何网站时,其链接看起来像 www.website.com/profile.php?id=username 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) 索引.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);
}