如何在 PHP 索引文件中获取 URL 路径?

How to get URL path in PHP index file?

我正在使用 cpanel 和 php 创建我的网站。

如何从 url http://example.com/id

中获取 ID

问题是,当我尝试获取 url 时,我正在重定向到名称为 id 的文件 404 错误!

我无法在 index.php 页面中获取路径?

例如当我试图得到这个时 url

http://example.com/01OWUY

我想用

得到01OWUY
$link .= $_SERVER['REQUEST_URI']; 

代码,但我会遇到 404 错误

更新:

每个用户都有一个id

有了这个id他就可以看到她的信息

例如 ID 为 01OWUY 的用户可以从数据库中看到她的信息 像这样 ->

<?php

require 'config.php';

//Database connection
$conn = mysqli_connect(SERVERNAME, USERNAME, PASSWORD, DBNAME);

$user = handle_user($conn, $_SERVER['REQUEST_URI'])
?>

函数是这个->

// Return true if link is active
function handle_user($conn, $linkId)
{
    $sql = "SELECT *FROM users WHERE link_id = '" . $linkId . "'";
    $result = $conn->query($sql);

    // get user data from db
    if ($result->num_rows > 0) {
        return $result;
    }
    return false;
}

但我收到 404 错误!!!

如果文件不存在,您将需要加载index.php。

这是 php 框架中非常常见的做法,例如 Laravel。

.htaccess 文件

# Not for real file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url= [QSA,L]

要实现此功能,您必须 mod_rewrite enabled

然后您将在 index.php 文件中获得可用数据。 你仍然需要 sanitize the input $_SERVER["REQUEST_URI"]


轻量级框架推荐包括routing features:

流明

https://lumen.laravel.com/