NSaid
NSaid

Reputation: 751

How to use a username as part of the url in php

Let say I have a site

www.mysite.com

Is there anyway to have to have user page urls be

www.mysite.com/username

instead of the usual

www.mysite.com/user.php?id=whatever

I would like to know if this is possible in php without having multiple folders and index pages. I would like to avoid the folder method because from my understanding you would have an issue with efficiency especially if you have to bounce from one user to another. I would like to do this method because it is a lot easier for someone to say get my info from

www.mysite.com/username

than the other option. Any help (tutorials, sites, etc) would be appreciated. Thanks in advance.

Upvotes: 1

Views: 142

Answers (3)

moonwave99
moonwave99

Reputation: 22817

Apply front controller pattern with any kind of router [e.g. klein], then you'll need a single, universal .htaccess file in your webroot:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

Upvotes: 2

Alex Kapustin
Alex Kapustin

Reputation: 2429

I would like to know if this is possible in php without having multiple folders and index pages.

Yes, its possible. You can do it redirecting all requests to your index.php and process this url (route) manually

sample .htaccess for redirecting all request to your index.php

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?route=$1 [L,QSA]

BUT implemention of

www.mysite.com/username

is not easy thing. You have to know all your system usrls such as /register, /login, /post, ... etc and dont allow to register these usernames. I recomend you implement this scheme:

www.mysite.com/~username or www.mysite.com/user/username

Upvotes: 2

anubhava
anubhava

Reputation: 784908

Yes sure, use this rule in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /user.php?id=$1 [L,QSA]

Upvotes: 1

Related Questions