How to use username in URL ??

Discussion in 'PHP' started by tomsign, Jul 16, 2010.

  1. #1
    Hi.. friend,


    i am creating small webapp with php

    where mydomain.com/profile.php?id=12345

    this was users profile page ,and then with get method ,i fetch user data from database as below code

    $userid=$_GET['id'];
    $qry="select * from `users` where userid ='$userid'";
    echo $qry;
    $result=mysql_query($qry);
    $userinfo = mysql_fetch_array($result);
    $u_name=$userinfo['name'];
    $u_userid=$userinfo['userid'];
    $u_gender=$userinfo['gender'];


    but i want my url like this mydomain.com/username

    without .php or anything can any one help me to fix this

    get method doesn't work here any other option?
     
    tomsign, Jul 16, 2010 IP
  2. bigmax

    bigmax Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You've got to play around with the .htaccess file and look up about RewriteCond and RewriteRule statements. I'm not really acquainted with these, but once you setup a redirect rule, then it would basically point all mydomain.com/xxx requests to your profile.php page which will output the necessary user info. Something along those lines.
     
    bigmax, Jul 16, 2010 IP
  3. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    bigmax is correct, you will need to use .htaccess. This allows you to manipulate incoming urls to suite your code (among many other things).

    Go to your webroot and create a file called .htaccess, and add this to it:
    
    Options +FollowSymlinks
    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^user/([_a-z0-9\-]+)/?$ /profile.php?username=$1 [NC,L]
    
    Code (markup):
    So now when you go to domain.com/user/MyUsername it will fire the profile.php script.
    Notice we don't use domain.com/MyUsername, as this would interfere with your websites directories. (if a user decided they wanted the username 'contact.html' for example)

    Now your PHP code would look something like:
    
    <?php
    	$userid = $_GET['username'];
    	$qry='select * from `users` where `name` = "' .$userid . '"';
    	echo $qry;
    	$result=mysql_query($qry);
    	$userinfo = mysql_fetch_array($result);
    	$u_name=$userinfo['name'];
    	$u_userid=$userinfo['userid'];
    	$u_gender=$userinfo['gender'];
    ?>
    
    PHP:
     
    Deacalion, Jul 16, 2010 IP