Tags

, ,


Sometime we need to get direct access any specific page. We need a user profile page http://www.domain.com/username, but our actual url is http://www.domain.com/profile/profile.php?username=Abc

I’m trying to describe how to make the url friendly, I used .htaccess and php for rewrite the url.
.htaccess

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?uri=$1 [QSA,L]

In this case the uri took parameter after index.php file.
So if url is http://www.domain.com/username
uri will have the value uri=useranme

We need following code to retrieve the parameter.

 $_SERVER['QUERY_STRING']

I followed the following way inside index.php file to get the username

  $flag = false; 
  if(isset($_SERVER['QUERY_STRING']))
  {
      $q = $_SERVER['QUERY_STRING'];
      $data = explode("=",$q);  // Assume uri=username 
      if(isset($data[0]) && isset($data[1]) && $data[0] == 'uri')
      {
          $a = $data[1];
          $q = "SELECT * FROM user_profiles WHERE user_profile_name = '$a'";
          $cnt = mysql_num_rows(mysql_query($q));
          if($cnt > 0)
          {
             include("profile/profile.php");
             $flag = true;
          }
          
      }
      
  }
if($flag == false)
{
   include("home.php") // your index or homepage 
}

So above code I tried to find the uri and check it on database if username/profile name exists or not. If it found I include the profile page. if not then include the homepage. After including profile.php page, all variables (only above include) are available in profile.php file.

its working with me very well.

You may have better solutions. But I need it very urgent that’s why I write the code in this way. If you have better solution please share your thoughts.

Advertisements