简体   繁体   中英

Sub-Folder to PHP Vanity urls

i am creating php social project which every user has his own profile ( vanity url ) like :

www.mysite.com/myname

and i used this codes :

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:

    Options +FollowSymlinks

    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME}.php -f

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

    RewriteCond %{REQUEST_FILENAME} >""

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

and this code works and if i typed www.mysite.com/username it show the profile of the user.

now iam asking to create a sub folder to the vanity url .. i mean if i typed www.mysite.com/username/info it echos info of the username which is stored in the database .. any ideas ?

Add

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

Before

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

The reason to add it before is that the second will match username/info also but redirect to the profile page.

I highly recommend Rewriting everything to one script called a Front Controller:

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

Then you can handle the url in front_controller.php and figure out which page to load. Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM