Facebook喜欢自定义个人资料网址PHP


Facebook Like Custom Profile URL PHP

制作网站,我想为我网站上所有用户(如Facebook(输入一个自定义个人资料URL。

在我的网站上,人们已经有一个像 http://sitename.com/profile.php?id=100224232 这样的页面

但是,我想为那些与其用户名相关的页面制作一个镜像。例如,如果您转到 http://sitename.com/profile.php?id=100224232 它会重定向到您 http://sitename.com/myprofile

我将如何使用PHP和Apache来做到这一点?

没有文件夹,没有索引.php

只需看看本教程。

编辑:这只是一个总结。

0( 上下文

我假设我们想要以下网址:

http://example.com/profile/userid(通过 ID 获取个人资料(
http://example.com/profile/username(通过用户名获取个人资料(
http://example.com/myprofile(获取当前登录用户的个人资料(

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:

在索引中.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);

使用 url http://example.com/profile/19837,$command将包含:

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)

现在,我们必须调度 URL。我们在索引中添加此内容.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(配置文件.php

现在在配置文件.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);
}

结语

我希望我足够清楚。我知道这段代码并不漂亮,也不是 OOP 风格,但它可以提供一些想法......