Implementing vanity URL for individual users in PHP

╄→尐↘猪︶ㄣ 提交于 2019-12-24 19:00:09

问题


How would one go about implementing a vanity URL for each user in PHP? I'm implementing my web-app's login system as a tweaked version of the Drax LLP Login system.

So, each user should be able to modify his profile which will finally appear on his vanity URL .. like xyz.com/user.

Any tips / ideas? Thanks..


回答1:


Here's an example of the files involved:

.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

index.php

<?php
function getWebPath() {
    $location = "";

    // Read the relative URL into an array
    if(isset($_SERVER['HTTP_X_REWRITE_URL'])) { // IIS Rewrite
        $location = $_SERVER['HTTP_X_REWRITE_URL'];
    } elseif(isset($_SERVER['REQUEST_URI'])) { // Apache
        $location = $_SERVER['REQUEST_URI'];
    } elseif(isset($_SERVER['REDIRECT_URL'])) { // Apache mod_rewrite (breaks on CGI)
        $location = $_SERVER['REDIRECT_URL'];
    } elseif(isset($_SERVER['ORIG_PATH_INFO'])) { // IIS + CGI
        $location = $_SERVER['ORIG_PATH_INFO'];
    }

    return $location;
}

$location = getWebPath();

print_r($location);

The function above should become a method in your front controller class somewhere. You just need to subtract your base path from $location so you're left with the virtual path. Then you can do whatever you want -- e.g. simply split on '/' and then work your way through the path, passing each remainder to the next controller depending on the URI. You could also write more complicated routing rules using regular expressions (something Django and quite a few other frameworks do).

For example: /profiles/hardik988

Would be passed to the controller in charge of 'profiles', which then decides what to do with the remainder of the path. It would likely look up the username and display the appropriate template.




回答2:


It's relatively simple: you have a mod_rewrite rule to map requests to www.domain.com/username to something like www.domain.com/users/username.

However, you then need to be aware what to prohibit from being a username, as I presume you'll have other top-level pages such as www.domain.com/about or www.domain.com/terms. Therefore, you don't want people registering about and terms as usernames.



来源:https://stackoverflow.com/questions/3776315/implementing-vanity-url-for-individual-users-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!