子文件夹到PHP虚荣网址

时间:2013-08-02 17:13:09

标签: php .htaccess vanity-url

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

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

    上的RewriteEngine

    RewriteCond%{REQUEST_FILENAME} .php -f

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

    RewriteCond%{REQUEST_FILENAME}&gt;“”

    RewriteRule ^([^。] +)$ profile.php?u = $ 1 [L]

  2. 并且此代码有效,如果我输入www.mysite.com/username,则会显示该用户的个人资料。

    现在iam要求为虚荣网址创建一个子文件夹...我的意思是如果我输入www.mysite.com/username/info 它回应了存储在数据库中的用户名信息..任何想法?

2 个答案:

答案 0 :(得分:1)

添加

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]

之前添加它的原因是第二个也会匹配用户名/信息,但会重定向到个人资料页面。

答案 1 :(得分:1)

我强烈建议将所有内容重写为一个名为Front Controller的脚本:

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

然后您可以处理front_controller.php中的网址并确定要加载的网页。类似的东西:

<?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
}