Andrea Fabbri
Andrea Fabbri

Reputation: 63

Getting variables in the URL with htaccess

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?

Upvotes: 0

Views: 112

Answers (3)

Hardik
Hardik

Reputation: 1411

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]

Upvotes: 1

mronus
mronus

Reputation: 1

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

Upvotes: 0

tim.baker
tim.baker

Reputation: 3307

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.

Upvotes: 0

Related Questions