PHP虚荣URL的子文件夹



我正在创建php社交项目,每个用户都有自己的个人资料(虚荣url),比如:

www.mysite.com/myname

我用了这个代码:

1.profile.php

<?php
ob_start();
require("connect.php");
if(isset($_GET['u'])){
    $username = mysql_real_escape_string($_GET['u']);
    if(ctype_alnum($username)){
        $data = mysql_query("SELECT * FROM members WHERE username = '$username'");
        if(mysql_num_rows($data) === 1){
            $row = mysql_fetch_assoc($data);
            $info = $row['info'];
            echo $username."<br>";
        }else{
            echo "$username is not Found !";
        }
    }else{
        echo "An Error Has Occured !";
    }
}else{
    header("Location: index.php");
}?>
  1. .htaccess:

    选项+FollowSymlinks

    上的重写引擎

    重写代码%{REQUEST_FILENAME}.php-f

    重写规则^([^.]+)$$1.php[NC]

    重写结束%{REQUEST_FILENAME}>"

    重写规则^([^.]+)$profile.php?u=$1[L]

这个代码有效,如果我键入www.mysite.com/username,它会显示用户的配置文件。

现在我要求创建一个子文件夹到虚荣网址。。我的意思是,如果我键入www.mysite.com/username/info它回显存储在数据库中的用户名信息。。有什么想法吗?

我强烈建议将所有内容重写为一个称为前端控制器的脚本:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ front_controller.php [L]

然后,您可以在front_controller.php中处理url,并确定要加载哪个页面。类似于:

<?php
// If a page exists with a `.php` extension use that
if(file_exists(__DIR__ . $_SERVER['REQUEST_URI'] . '.php'){
    require __DIR__ . $_SERVER['REQUEST_URI'] . '.php';
    exit;
}
$uri_parts = explode('/', $_SERVER['REQUEST_URI']);
$num_uri_parts = count($uri_parts);
// For compatability with how you do things now
// You can change this later if you change profile.php accordingly
$_GET['u'] = $uri_parts[0];
if($num_uri_parts) == 1){
    require __DIR__ . 'profile.php';
    exit;
}
if($num_uri_parts) == 2){
    if($uri_parts[1] === 'info'){
        require __DIR__ . 'info.php';
        exit;
    }
    // You can add more rules here to add pages
}

添加

RewriteRule ^([^.]+)/info url/to/info/page/info.php?u=$1 [NC, L] #L = last [don't match any other rewrites if this matches] 

之前

RewriteRule ^([^.]+)$ $1.php [NC]

之前添加它的原因是第二个也会匹配username/info,但会重定向到配置文件页面。

最新更新