首页 文章

子文件夹到PHP虚荣网址

提问于
浏览
1

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

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");
}?>
  • .htaccess:

选项FollowSymlinks

RewriteEngine on

RewriteCond% .php -f

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

RewriteCond%>“”

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

这个代码有效,如果我输入www.mysite.com/username,它会显示用户的 Profiles .

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

2 回答

  • 1

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

    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
    }
    
  • 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]
    

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

相关问题