0

I need that when I write http://www.mysite.com/username the username is sent as a parameter to index.php

example: http://www.mysite.com/index.php?user=username

how can I do with htaccess? you have other ideas?

Andrea Fabbri
  • 63
  • 1
  • 2
  • 13

3 Answers3

1

Please write rule in your htaccess like this :

RewriteEngine On
RewriteRule ^([a-zA-Z0-9-/]+)$ index.php?uniqname=$1 [QSA]
RewriteRule ^([a-zA-Z0-9-/]+)/$ index.php?uniqname=$1 [QSA]

To add folders use this

RewriteEngine On
RewriteRule ^avatars/([a-zA-Z0-9-/]+)$ index.php?uniqname=$1 [QSA]
RewriteRule ^avatars/([a-zA-Z0-9-/]+)/$ index.php?uniqname=$1 [QSA]
Hardik
  • 1,429
  • 2
  • 19
  • 37
  • Why not `RewriteRule ^([a-zA-Z0-9-/]+)/?$ index.php?uniqname=$1 [QSA]` instead? – h2ooooooo Feb 20 '13 at 13:34
  • if there is any thing wrong in my answer then please guide me – Hardik Feb 20 '13 at 13:42
  • perfect, just that if I have folders? example if I http://mysite.com/avatars But I also have a folder called "avatars" how can I do? – Andrea Fabbri Feb 20 '13 at 13:45
  • i think you want to make like this http://www.mysite.com/avatars/username Am I right? – Hardik Feb 20 '13 at 13:49
  • if my answer is helpful to you then please vote this answer so it will be useful to others too. – Hardik Feb 20 '13 at 13:59
  • @Hardik The reason I added `/?` is because `?` in regex means `repeated 0 or 1 time`, then therefore you wouldn't need your second line (as it'd already be included by saying "either end with a slash or don't"). – h2ooooooo Feb 20 '13 at 14:12
  • @Hardik I need some names for this rule is not applied because on the server, there are folder might be called as a user name? – Andrea Fabbri Feb 20 '13 at 15:31
0

So you want to be able to read the username variable in the PHP of the requested page?

In PHP you would do this, in it's most basic form

    <?php echo $_GET['username']; ?> // That will print the variable value on the page

Important. If you are using this to get or edit data in a database you need to clean or sanitize that variable first to prevent against SQL Injection Attacks. A rough example of this is as such

    <?php 
    $username = mysql_real_escape_string($_GET['username'];
    echo $username;
    ?>

You may also want to have more of a read of PHP GET and POST variables.

Community
  • 1
  • 1
tim.baker
  • 3,109
  • 6
  • 27
  • 51
0

You can use following RewriteRules:

//Only one parameter that defines username
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?username=$1

//If you need second parameter or a number only parameter
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)$ index.php?username=$1&paramnumber=$2
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ index.php?username=$1&paramstring=$2
mronus
  • 1
  • 1