Create SEO Friendly URLs With Mod Rewrite and PHP – Part II
By on October 31st, 2008

More than a year back I had written a tutorial on creating SEO Friendly URLs with Mod Rewrite and PHP, where I had explained the basic SEO concepts of rewriting URLs to make them SEO friendly.

Though It has been over a year, numerous emails and comments have dropped in for me to write the second part of the series, so here it is :-)

In the first part I had explained the basic changes you would require to do in the .htaccess file to create SEO friendly URLs, the post explained how you can internally redirect a URL to any PHP page that is stored on your web server.

In this post I will explain how you need to modify the PHP files so that it will generate the SEO friendly links for your website.

The original URL we were dealing with would create URLs as this one http://www.yoursite.com/product.php?productid=2&categoryid=3, here is a example PHP code of that generates this URL. I am leaving the Database connection code out of the example to keep the examples short.

   1: <?php
   2: // Retrieve all products from the table
   3: $result = mysql_query("SELECT product_id, product_title, category_id  FROM products") or die(mysql_error());  
   4:  
   5: //fetch the result array
   6: $products = mysql_fetch_array( $result );
   7:  
   8: //iterate the products and create links
   9: foreach($products as $product) {
  10:     $product_id = $product['product_id'];
  11:     $product_title = $product['product_title'];
  12:     $category_id = $product['category_id'];
  13:     //write the URL as http://www.yoursite.com/product.php?productid=2&categoryid=3
  14:     echo "<a href='http://www.yoursite.com/product.php?productid=$product_id&amp;categoryid=$category_id'>$product_title</a>";
  15: }
  16: ?>

In order to generate SEO friendly links you will have to change the way you write the links to the page, the changes are pretty minor and here is the example code for writing the SEO friendly URLs on your pages with PHP.

   1: <?php
   2:  
   3: //iterate the products and create links
   4: foreach($products as $product) {
   5:     $product_id = $product['product_id'];
   6:     $product_title = $product['product_title'];
   7:     $category_id = $product['category_id'];
   8:     //write the URL as http://www.yoursite.com/product/13/3/2-gb-mp3-player.htm
   9:     $product_title_url = gen_seo_friendly_titles($product_title)
  10:     echo "<a href='http://www.yoursite.com/product/$product_id/$category_id/$product_title_url.html'>$product_title</a>";
  11: }
  12:  
  13:  
  14: function gen_seo_friendly_titles($title) {
  15:     $replace_what = array('  ', ' - ', ' ',    ', ', ',');
  16:     $replace_with = array(' ', '-', '-', ',', '-');
  17:     
  18:     $title = tolowercase($title);
  19:     $title = str_replace($replace_what, $replace_with, $title);
  20:     return $title;
  21:  
  22: }
  23:  
  24: ?>

In the code example, I changed the URL structure to match what we created in the .htaccess file, I am changing the product title to SEO friendly version by calling the method gen_seo_friendly_titles which takes the product title as a parameter.

The gen_seo_friendly_titles method basically lower cases the product name and replaces spaces and dashes to form a proper URL. You can use your own replacements in the method as you see it fit.

Also as you can see I am not directly manipulating the $product_title itself and saving it in another variable called $product_title_url, since we will be using the $product_title as the anchor text and would want it to remain as it is.

This concludes the series of creating SEO friendly URLs with Mod Rewrite and PHP, hopefully this should answer the many emails and comments about where the second part is :-), feel free to drop your question in the comments.

Tags:
Author: Keith Dsouza Google Profile for Keith Dsouza
I am the editor-in-chief and owner of Techie Buzz. I love coding and have contributed to several open source projects in the past. You can know more about me and my projects by visiting my Personal Website. I am also a social networking enthusiast and can be found active on twitter, you can follow Keith on twitter @keithdsouza. You can click on my name to visit my Google+ profile.

Keith Dsouza has written and can be contacted at keith@techie-buzz.com.
  • http://tech.shantanugoel.com/ Shantanu Goel

    Keith, your posts appears cut off/hidden slightly on the right side to me. Am using FF3 under linux..

  • shubhodeep

    thanks for the article. I emailed you and got a reply so early. thanks once again.

  • shubhodeep

    yeah, as shantanu pointed out, the post is a bit cut off on the right hand side. I’m suing FF3 under Vista.

  • Keith Dsouza

    @Shantanu @shubhodeep Thanks for the heads up, the issue has been fixed now

  • sandip

    include_once “myconnect.php”;
    include_once “date_time_format.php”;

    if(isset($_REQUEST["cid"]))
    {
    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_pid=” . $_REQUEST["cid"]);
    $rs=mysql_num_rows($cat_query);

    if(($rs<=0)||($_REQUEST["cid"]==0))
    {
    header(“Location:”.”selloffers.php?cid=”.$_REQUEST["cid"]);
    die();
    }

    }

    function main()
    {
    $keyword=”";
    if(isset($_REQUEST["keyword"])&&($_REQUEST["keyword"]“”))
    {
    $keyword=$_REQUEST["keyword"];
    }

    $config=mysql_fetch_array(mysql_query(“select * from sbbleads_config”));
    if(($config["sb_image_magik"]==”enable”))
    {
    $img_path=”thumbs1/”;
    $img_pmt=”";
    }
    else
    {
    $img_path=”uploadedimages/”;
    $img_pmt=”width=”.$config["sb_th_width"].” height=”.$config["sb_th_width"];
    }

    $cid=0;
    if(isset($_REQUEST["cid"])&&($_REQUEST["cid"]“”))
    {
    $cid=$_REQUEST["cid"];
    $sbqu_off=”update sbbleads_categories set sb_visit_sell=sb_visit_sell+1 where sb_id=$cid”;
    mysql_query($sbqu_off);
    }

    /*$sell_num=mysql_num_rows(mysql_query(“select * from sbbleads_offers where sb_approved=’yes’”));
    $buy_num=mysql_num_rows(mysql_query(“select * from sbbleads_offers_buy where sb_approved=’yes’”));
    $product_num=mysql_num_rows(mysql_query(“select * from sbbleads_products where sb_approved=’yes’”));
    $profile_num=mysql_num_rows(mysql_query(“select * from sbbleads_companyprofiles where sb_approved=’yes’”));*/

    $catname=”";
    $category=0;

    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_id=” . $cid );
    if ($cat=mysql_fetch_array($cat_query))
    {
    $catname=$cat["sb_cat_name"];
    $category=$cat["sb_id"];
    }

    $catpath=”";
    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_id=” . $cid );
    while ($rs=mysql_fetch_array($cat_query))
    {
    $catpath =” > ” .$rs["sb_cat_name"].”“.$catpath;
    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_id=” . $rs["sb_pid"] );
    }
    ?>

    <input name=”keyword” type=”text” value=”" size=”40″>
      
    Sell Offers
    Buy Offers
    Products Catalogs
    Company Profiles

     

     

     Advance Search  

     Home

    ↓  Sell Offers
    →  <a href=”cat_buy.php<?php if($cid0) echo “?cid=”.$cid;?>”>Buy
    Offers
    →  <a href=”cat_products.php<?php if($cid0) echo “?cid=”.$cid;?>”>Products
    →  <a href=”cat_profiles.php<?php if($cid0) echo “?cid=”.$cid;?>”>Companies

    Browse Sell Offers

    NOW() $sbcat_str”;
    $sboff_count=mysql_num_rows(mysql_query($sbq_off_cat));

    $sbq_buy_cat=”select * from sbbleads_offer_cats_buy, sbbleads_offers_buy where sb_approved=’yes’ and sbbleads_offers_buy.sb_id=sbbleads_offer_cats_buy.sb_offer_id and DATE_ADD(sb_postedon,INTERVAL “.$config["sb_expiry_buy"].” MONTH) > NOW() $sbcat_str”;
    $sbbuy_count=mysql_num_rows(mysql_query($sbq_buy_cat));

    $sbq_product_cat=”select * from sbbleads_product_cats, sbbleads_products where sb_approved=’yes’ and sbbleads_products.sb_id=sbbleads_product_cats.sb_offer_id $sbcat_str”;
    $sbproduct_count=mysql_num_rows(mysql_query($sbq_product_cat));

    $sbq_profile_cat=”select * from sbbleads_profile_cats, sbbleads_companyprofiles where sb_approved=’yes’ and sbbleads_companyprofiles.sb_id=sbbleads_profile_cats.sb_profile_id $sbcat_str”;
    $sbprofile_count=mysql_num_rows(mysql_query($sbq_profile_cat));
    $sbtotal=$sboff_count;//$sboff_count+$sbbuy_count+$sbproduct_count+$sbprofile_count;
    //die();
    if($cnt%3==1)
    {
    ?>
     

    <a href=”index.php?cid=”>
    <a href=”cat_sell.php?cid=”>()

     Featured Offers

    NOW() order by sb_id desc”;
    $sbrs_off=mysql_query($sbq_off);
    $num_rows=mysql_num_rows($sbrs_off);
    $max_allowed=$config["sb_cat_featured"];

    $number[0]=-1;
    if($num_rows>$max_allowed)
    {
    for($i=0;$i<$max_allowed;$i++)
    {
    $unique=0;
    while($unique==0)
    {
    $j=rand(0,$num_rows-1);
    for($k=0;$k(count($number)-1))
    {
    $unique=1;
    }
    }
    $number[$i]=$j;

    }
    }// end if num > no_allowed
    /*for($k=0;$k<count($number);$k++)
    {
    echo $number[$k].” “;
    }*/
    $row=0;
    $cnt=0;
    $offer=mysql_fetch_array($sbrs_off);
    while (($offer)&&($cnt$max_allowed)
    {
    for($k=0;$k

    <? if ($images) {echo ““; } else
    {
    ?>
    <img src=”images/nopic.gif” >

     <a
    href=”view_offer.php?id=”>
    50)
    {
    echo substr($offer["sb_title"], 0, strrpos( substr($offer["sb_title"], 0, 50),’ ‘ ));
    }
    else
    {
    echo $offer["sb_title"];
    }
    ?>
    [

    ]

     Posted by

    [

    ] on

     
    100)
    {
    echo substr(strip_tags($offer["sb_description"]), 0, strrpos( substr(strip_tags($offer["sb_description"]), 0, 100),’ ‘ )) . “..”;
    }
    else
    {
    echo strip_tags($offer["sb_description"]);
    }
    ?>

    =$max_allowed))
    {
    ?>

     
    Default Ad
     

     
    Become a Gold member and your
    Offer will appear here.

    Default Ad
     

    Become a Gold member and your
    Offer will appear here.

  • sandip

    Right now below script is giving me url like this

    http://www.mysite.com/bb/cat_sell.php?cid=1

    where as i am looking for url like this

    http://www.mysite.com/bb/1/agriculture.html
    where 1 is cid of agriculture

    looking forward for your reply

    include_once “myconnect.php”;
    include_once “date_time_format.php”;

    if(isset($_REQUEST["cid"]))
    {
    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_pid=” . $_REQUEST["cid"]);
    $rs=mysql_num_rows($cat_query);

    if(($rs<=0)||($_REQUEST["cid"]==0))
    {
    header(“Location:”.”selloffers.php?cid=”.$_REQUEST["cid"]);
    die();
    }

    }

    function main()
    {
    $keyword=”";
    if(isset($_REQUEST["keyword"])&&($_REQUEST["keyword"]“”))
    {
    $keyword=$_REQUEST["keyword"];
    }

    $config=mysql_fetch_array(mysql_query(“select * from sbbleads_config”));
    if(($config["sb_image_magik"]==”enable”))
    {
    $img_path=”thumbs1/”;
    $img_pmt=”";
    }
    else
    {
    $img_path=”uploadedimages/”;
    $img_pmt=”width=”.$config["sb_th_width"].” height=”.$config["sb_th_width"];
    }

    $cid=0;
    if(isset($_REQUEST["cid"])&&($_REQUEST["cid"]“”))
    {
    $cid=$_REQUEST["cid"];
    $sbqu_off=”update sbbleads_categories set sb_visit_sell=sb_visit_sell+1 where sb_id=$cid”;
    mysql_query($sbqu_off);
    }

    /*$sell_num=mysql_num_rows(mysql_query(“select * from sbbleads_offers where sb_approved=’yes’”));
    $buy_num=mysql_num_rows(mysql_query(“select * from sbbleads_offers_buy where sb_approved=’yes’”));
    $product_num=mysql_num_rows(mysql_query(“select * from sbbleads_products where sb_approved=’yes’”));
    $profile_num=mysql_num_rows(mysql_query(“select * from sbbleads_companyprofiles where sb_approved=’yes’”));*/

    $catname=”";
    $category=0;

    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_id=” . $cid );
    if ($cat=mysql_fetch_array($cat_query))
    {
    $catname=$cat["sb_cat_name"];
    $category=$cat["sb_id"];
    }

    $catpath=”";
    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_id=” . $cid );
    while ($rs=mysql_fetch_array($cat_query))
    {
    $catpath =” > ” .$rs["sb_cat_name"].”“.$catpath;
    $cat_query=mysql_query(“Select * from sbbleads_categories where sb_id=” . $rs["sb_pid"] );
    }
    ?>

    <input name=”keyword” type=”text” value=”" size=”40″>
      
    Sell Offers
    Buy Offers
    Products Catalogs
    Company Profiles

     

     

     Advance Search  

     Home

    ↓  Sell Offers
    →  <a href=”cat_buy.php<?php if($cid0) echo “?cid=”.$cid;?>”>Buy
    Offers
    →  <a href=”cat_products.php<?php if($cid0) echo “?cid=”.$cid;?>”>Products
    →  <a href=”cat_profiles.php<?php if($cid0) echo “?cid=”.$cid;?>”>Companies

    Browse Sell Offers

    NOW() $sbcat_str”;
    $sboff_count=mysql_num_rows(mysql_query($sbq_off_cat));

    $sbq_buy_cat=”select * from sbbleads_offer_cats_buy, sbbleads_offers_buy where sb_approved=’yes’ and sbbleads_offers_buy.sb_id=sbbleads_offer_cats_buy.sb_offer_id and DATE_ADD(sb_postedon,INTERVAL “.$config["sb_expiry_buy"].” MONTH) > NOW() $sbcat_str”;
    $sbbuy_count=mysql_num_rows(mysql_query($sbq_buy_cat));

    $sbq_product_cat=”select * from sbbleads_product_cats, sbbleads_products where sb_approved=’yes’ and sbbleads_products.sb_id=sbbleads_product_cats.sb_offer_id $sbcat_str”;
    $sbproduct_count=mysql_num_rows(mysql_query($sbq_product_cat));

    $sbq_profile_cat=”select * from sbbleads_profile_cats, sbbleads_companyprofiles where sb_approved=’yes’ and sbbleads_companyprofiles.sb_id=sbbleads_profile_cats.sb_profile_id $sbcat_str”;
    $sbprofile_count=mysql_num_rows(mysql_query($sbq_profile_cat));
    $sbtotal=$sboff_count;//$sboff_count+$sbbuy_count+$sbproduct_count+$sbprofile_count;
    //die();
    if($cnt%3==1)
    {
    ?>
     

    <a href=”index.php?cid=”>
    <a href=”cat_sell.php?cid=”>()

     Featured Offers

    NOW() order by sb_id desc”;
    $sbrs_off=mysql_query($sbq_off);
    $num_rows=mysql_num_rows($sbrs_off);
    $max_allowed=$config["sb_cat_featured"];

    $number[0]=-1;
    if($num_rows>$max_allowed)
    {
    for($i=0;$i<$max_allowed;$i++)
    {
    $unique=0;
    while($unique==0)
    {
    $j=rand(0,$num_rows-1);
    for($k=0;$k(count($number)-1))
    {
    $unique=1;
    }
    }
    $number[$i]=$j;

    }
    }// end if num > no_allowed
    /*for($k=0;$k<count($number);$k++)
    {
    echo $number[$k].” “;
    }*/
    $row=0;
    $cnt=0;
    $offer=mysql_fetch_array($sbrs_off);
    while (($offer)&&($cnt$max_allowed)
    {
    for($k=0;$k

    <? if ($images) {echo ““; } else
    {
    ?>
    <img src=”images/nopic.gif” >

     <a
    href=”view_offer.php?id=”>
    50)
    {
    echo substr($offer["sb_title"], 0, strrpos( substr($offer["sb_title"], 0, 50),’ ‘ ));
    }
    else
    {
    echo $offer["sb_title"];
    }
    ?>
    [

    ]

     Posted by

    [

    ] on

     
    100)
    {
    echo substr(strip_tags($offer["sb_description"]), 0, strrpos( substr(strip_tags($offer["sb_description"]), 0, 100),’ ‘ )) . “..”;
    }
    else
    {
    echo strip_tags($offer["sb_description"]);
    }
    ?>

    =$max_allowed))
    {
    ?>

     
    Default Ad
     

     
    Become a Gold member and your
    Offer will appear here.

    Default Ad
     

    Become a Gold member and your
    Offer will appear here.

  • omer

    hi i am using your code for seo friendly urls but some how when i click the link that i have made it goes to that page and makes the url; friendly but the CSS appears to be missing when i visit through the lik that i have made as per your suggested method what should i do

  • Sergio

    Having problems, i’m getting the urls to work, but the page shows up with no styles

    Other than that, the article was great

    • http://keithdsouza.com Keith Dsouza

      @Sergio The problem will be seen, if you are using an external CSS stylesheet using relative path like /style.css or ../style.css, try changing the stylesheet to use a full path starting with http:// this should solve your problem.

  • Ravi Shankar

    I think this is best answer for any php developer that is handling url rewriting rules.

    But what would be the .htaccess file for this.

    Is it not require .htaccess file.

    thanks

  • http://www.texasairsalvage.com/main_view.php?editid1=20346 Loren Bond

    Hello, I'm having trouble with the return url.

    I'm using mod-rewrite to create a friendly url from a dynamic URL

    The Dynamic URL looks like this.. Airframe_list.php?editid1=123456

    I have written a friendly URL that looks like this..

    Airframe-123456-friendly-Test-Description.htm

    I'm using this to resolve the url.

    RewriteRule ^Airframe-Parts-([0-9]+)-(.*).htm$ main_view.php?editid1=$1 [R=301,NC,L]

    This works fine and the program executes correctly; however, after the page is called up I get the resolved url in the url line.

    I get this in the url line. > Airframe_list.php?editid1=123456

    I want this in the url line> Airframe-123456-friendly-Test-Description.htm

  • Rahul

    Keith
    Can you please tell me the exact location where i can change the
    relative css path to absolute path? In Which php file i can change the
    css path??

 
Copyright 2006-2012 Techie Buzz. All Rights Reserved. Our content may not be reproduced on other websites. Content Delivery by MaxCDN