SEO Friendly URLs with PHP
Wall Script
Wall Script
Wednesday, April 06, 2011

SEO Friendly URLs with PHP

This post explains how to create SEO friendly URL with dynamic content using PHP and .htaccess mod redirection. Friendly URLs improves your site search engines ranking. Before trying this you have to enable mod_rewrite.so module at httpd.conf. It’s simple just few lines of PHP code converting title data to clean URL format.

SEO Friendly URLs with PHP

Download Script     Live Demo

Database
Sample database blog table columns id, title, body and url.
CREATE TABLE blog
(
id INT PRIMARY KEY AUTO_INCREMENT,
title TEXT UNIQUE,
body TEXT,
url TEXT UNIQUE,
);

Publish.php
Contains PHP code. Converting title text to friendly url formate and storing into blog table.
<?php
include('db.php');
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}

if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title=mysql_real_escape_string($_POST['title']);
$body=mysql_real_escape_string($_POST['body']);
$title=htmlentities($title);
$body=htmlentities($body);
$date=date("Y/m/d");
//Title to friendly URL conversion
$newtitle=string_limit_words($title, 6); // First 6 words
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);
$url=$date.'/'.$newurltitle.'.html'; // Final URL
//Inserting values into my_blog table
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
}
?>
//HTML Part
<form method="post" action="">
Title:
<input type="text" name="title"/>
Body:
<textarea name="body"></textarea>
<input type="submit" value=" Publish "/>
</form>

Article.php
Contains HTML and PHP code. Displaying content from blog table.
<?php
include('db.php');
if($_GET['url'])
{
$url=mysql_real_escape_string($_GET['url']);
$url=$url.'.html'; //Friendly URL 
$sql=mysql_query("select title,body from blog where url='$url'");
$count=mysql_num_rows($sql);
$row=mysql_fetch_array($sql);
$title=$row['title'];
$body=$row['body'];
}
else
{
echo '404 Page.';
}
?>
//HTML Part
<body>
<?php
if($count)
{
echo "<h1>$title</h1><div class='body'>$body</div>";
}
else
{
echo "<h1>404 Page.</h1>";
}
?>
</body>

.htaccess
URL rewriting file. Redirecting original URL 9lessons.info/article.php?url=test.html to 9lessons.info/test.html
RewriteEngine On

RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1

db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
web notification

111 comments:

  1. Good Post Sri..

    Can u help me pls..

    I can not see any changes in my site, is there any problum in .htaccess and can u sent me a .htaccess fil..

    Thanks,
    Vishal
    [email protected]

    ReplyDelete
  2. Great article infact but when we put _ in title it shows error.So better throw _also.

    Very nice

    ReplyDelete
  3. The code don't work with special characters like ç Ç é í ó and !@#$%¨&*().

    If have some this characters break the code.

    ReplyDelete
  4. good article but php is very slow and not good for big web application..

    ReplyDelete
  5. Great job! Everything is working properly, there is only superfluous comma - in table creation at the end of "url TEXT" :)

    ReplyDelete
  6. Great article :) I appreciate your work.

    Below link is basic rewrite condition.
    http://phpcreating.blogspot.com/2010/02/url-rewriting.html

    Thanks
    Bhargav Anadkat

    ReplyDelete
  7. Great you helped me allot

    Thanks

    ReplyDelete
  8. wow it's cool...
    although I do not know about PHP
    good good

    ReplyDelete
  9. i think the problem for this code is the friendly url save to the database, there will be a scenario that the title needs to be change, it would be better that your friendly url is created on the fly and not to be database.

    ReplyDelete
  10. What about the Polish letters ?

    ReplyDelete
  11. What about the Polish letters eg. ąęśćłżźó

    ReplyDelete
  12. I can not see the point to do this with php.

    ReplyDelete
  13. @mercs

    Unicode support add this tag on header

    <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />

    ReplyDelete
  14. //good article but php is very slow and not good for big web application..//

    Facebook is a total php site.

    ReplyDelete
  15. php,asp,ruby or any.. Doesnt matter, php is not slow, it depends on how you create your structure. And how you optimize your query

    ReplyDelete
  16. nice...good job...i will use in my site

    ReplyDelete
  17. Hey,nice tutorial

    ReplyDelete
  18. Nice..
    How-to publish jquery with this?
    Thx

    ReplyDelete
  19. @Srinivas Tamada

    You don't need the http-equiv attributes. Browser's ignore them so all you need is charset.

    <meta charset=utf-8>

    As well to fix a bug in IE to stop code injection it needs to be in the first 150kb of the header so put it above <title> just after the <head> tag.

    ReplyDelete
  20. The URL should be unique. Id you have 2 post with the title 'Test', it'll show the first 'Test' post only. I suggest combining post ID and the post title together to create a unique URL.

    Example: test-1.html, test-2.html, etc...

    ReplyDelete
  21. Yes title, url should be UNIQUE -> Updated

    ReplyDelete
  22. Hello, I was just wondering if you can do a tutorial, about facebook like notification system? It would be really nice :D. Your blog it's great.

    ReplyDelete
  23. Hello Srinivas...
    can you give me example insert url like test-1.html, test-2.html, etc... if title same? thanks before...

    ReplyDelete
  24. Hi great post, It's easy to create friendly urls with php and mysql. Keep up the good work!

    ReplyDelete
  25. nice...good job...i will use in my site

    ReplyDelete
  26. hey, but turkish shows corrupted characters...

    ReplyDelete
  27. @ good article but php is very slow and not good for big web application..

    how about Facebook, is it big enough?

    @ I can not see the point to do this with php.

    This could give you a good ranking for your PHP website on Google Search results

    ReplyDelete
  28. For .htaccess you could do this:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ article.php?url=$1 [PT,L]

    What this will do is first check if the request IS NOT an actual file and folder, then it is passed on to article.php.

    With article.php, you check if the request exists in the database, if not then display a Page Not Found message

    ReplyDelete
  29. I dont understand where I m wrong..
    ı m always taking "Not URL Available 404." error.. :(
    I did everything , but results not so good.. , Srivinas please help me.Thank you,

    ReplyDelete
  30. 404 Error please check .htaccess code

    ReplyDelete
  31. can we use unicode in URL like this(2011/05/20/शुल्कवृद्धि-रोक्न) ?? I tried it but didn't work. Can we fix it??

    ReplyDelete
  32. Srini, I am a regular lurker at your site but do not post much. I really like your articles since they are very well written and, most importantly, love the baby steps.

    Also on this topic of .htaccess the following link is also very exhaustive and helpful.

    http://corz.org/serv/tricks/htaccess2.php

    ReplyDelete
  33. Wowwwww... Srinivas Great Article!!!

    I speak spanish, but i can understad a few english, and thank for this article, it´s difficult to find an article like this in spanish!

    Gracias y Saludos desde Mexico!!

    ReplyDelete
  34. How should db.php look like?

    ReplyDelete
  35. boss, thanks a lot for this article. its really helpful for me. A lot of time i search for apache url rewrite on search engine but i cant find one like this. this is great.

    ReplyDelete
  36. Related part:
    .htaccess
    URL rewriting file. Redirecting original URL 9lessons.info/article.php?url=test.html to 9lessons.info/test.html

    You say "redirecting"... But it is not redirecting. It is only the standard way to make seo friendly urls. NOT for redirecting old dynamic urls to sef ones...

    ReplyDelete
  37. hi i m yogesh
    its give some error
    (The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.)

    now wat to do ??

    ReplyDelete
  38. Srinivas Great Article but it is not working with Arabic Characters :(

    Can you please make a separate article for Unicode Characters in URLs?

    Thanks

    ReplyDelete
  39. who does this code mean?

    RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1

    ReplyDelete
  40. This code is very useful but i want to something like this.
    http://codedunia.in/c-language/introduction-to-c-language/
    I do this task but when anyone type:
    http://codedunia.in/c-language/introduction-to-c-language.php then it also redirect to:
    http://codedunia.in/c-language/introduction-to-c-language/
    Please give me the solution either here or to my facebook msg http://facebook.com/yogidreamss

    ReplyDelete
  41. =( the htaccess doesnt work ! i use Amini htaccess =) Thx =) excelent example... =)

    ReplyDelete
  42. how to change url http://www.findtoget.com/review.php?getid=o-H1yn1o&creed-one-last-breath.mp4.html

    to
    http://www.findtoget.com/review/getid/o-H1yn1o/creed-one-last-breath.mp4.html

    sendme file .htaccess for that

    [email protected]

    ReplyDelete
  43. Hello Sir, am unable to redirect the page can you please provide me .htaccess mod_rewrite.so code Please help me in this. Thanks

    ReplyDelete
  44. I'm not that satisfied..

    Try "This $ is a test"
    and you will get "This-$-is---.html" in your live example.

    or with "¶ ÄöÜ" you'll get "¶-Ã�öÃ�.html"

    -not very se friendly url's...

    ReplyDelete
  45. this is a horrible approach with horrible code organization. Very bad.

    ReplyDelete
  46. very interesting post. if you want to read a post similar to this go to http://our-knowledge-base.blogspot.com/2012/04/making-clean-string-for-seo-friendly.html

    ReplyDelete
  47. Thank you for this :D Im new to SEO so this helpful for a start

    ReplyDelete
  48. this is my link for website.Not in wordpress
    http://testifyforisrael.com/index.php?page=page&id=19

    i want like this http://testifyforisrael.com/index.php/our-mission

    rply me asap.

    ReplyDelete
  49. Thanks for this great information. Its really truly quality information.

    ReplyDelete
  50. Great post, useful information. I used to use Underscores myself haha, but the dashes look a lot cleaner if i do say so myself.

    ReplyDelete
  51. Hi Sir,
    i am working on your friendly url articles but i am facing problem. i have 2 pages mobile_phones.php and mobile_features.php

    RewriteEngine On

    RewriteRule ^([a-zA-Z0-9-/]+).html$ mobile_phones.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ mobile_phones.php?url=$1

    RewriteRule ^([a-zA-Z0-9-/]+).html$ mobile_features.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ mobile_features.php?url=$1

    and just upper two lines are working , i mean when we click on category they get mobiles and show on mobile_phones.php and when i click on mobile features it do not redirect to mobile_features.php it again redirect to mobile_phones.php i am very confused kindly help me in this matter i will appreciate.

    Thank You So Much

    ReplyDelete
  52. I test your script in my local server. but, it doesn't work, i opened mod_rewrite in httpd.conf. pls, alittle help me.

    ReplyDelete
  53. Hi Admin,

    Good work for this code, but i faced some problem in .htaccess file..


    RewriteEngine On

    RewriteRule ^([a-zA-Z0-9-/]+).html$ test1.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ test1.php?url=$1

    RewriteRule ^([a-zA-Z0-9-/]+).html$ test2.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ test2.php?url=$1

    First two lines its working fine, second line of
    RewriteRule ^([a-zA-Z0-9-/]+).html$ test2.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ test2.php?url=$1

    Not working how to give multiple page within .htaccess fils. Can you please let me know Admin.

    Thanks

    ReplyDelete
  54. The authoritative nature of URLs has decreased with time but it still doesn't hurt to have a keyword rich URL.

    ReplyDelete
  55. where is the db.php??
    is require a db.php

    ReplyDelete
  56. Valuable information and excellent post you got here! I would like to thank you for sharing your thoughts and time into the stuff you post.Very informative tips.

    ReplyDelete
  57. your post is very usefull and helpfull .

    ReplyDelete
  58. nice info,, but
    howto with replace (/,&.) with (-)?
    thanks

    ReplyDelete
  59. thanks for sharing this information..

    ReplyDelete
  60. RewriteEngine On

    RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1

    what is the setting in php.ini
    plz [email protected]

    ReplyDelete
  61. Hey i have many links...

    1: http://mysite.com/?nav=display&file=15
    2: http://mysite.com/?nav=profile&id=1
    etc,,,

    how to do:
    1: http://mysite.com/files/filename
    2: http://mysite.com/username


    Advance thanks

    ReplyDelete
  62. by applying your tutorial,
    url is generating like this :
    http://localhost/clean_url/article.php?url=2013/02/03/facebook.html
    but i want url look like this :
    http://localhost/clean_url/2013/02/03/facebook.html

    so how can i do that.

    ReplyDelete
  63. Great article.
    Finally I can understand SEO work.
    this simple explanation indeed.
    great work srinivas.

    ReplyDelete
  64. how can i convert

    login.php

    to

    login.html

    with.htaccess

    any one know that.

    ReplyDelete
  65. Hi,

    I did all the changes properly but it is redirecting to my main site. It's not working please help me.

    ReplyDelete
  66. Thanks its working.
    This is simple and use full article.

    Thanks Srinivas.

    ReplyDelete
  67. Nice one, and can you give full details, or a breif tutorial about ".htaccess" because, you've given one format, but i think still there are many formats, like
    "st.com/article.php?id=201&title=MyPage" to
    "st.com/article/My-Page"
    etc...
    I am seriously in need of this kind of links...

    ReplyDelete
  68. Pretty component of content. I simply stumbled upon your blog and in accession capital to claim that I get in fact loved account your weblog posts. Any way I’ll be subscribing to your feeds and even I fulfillment you get right of entry to consistently fast.

    ReplyDelete
  69. how do it. in nginx server? nginx server cant read .htaccess. please help me. urgent. thanks before

    ReplyDelete
  70. After a long search i came across your post. Your post has really worked me through the process of converting dynamic url to seo friendly url for my website.
    It is indeed a nice one.

    ReplyDelete
  71. VERY COOOOOOOOOOOOOOOOL
    I LOVE YOU 9LESSON TEAM
    CHEEEEEEEEEERS
    LOVE THIS TUROIAL>

    VERY GOOOOOOOOOOOOOOOOOOD
    HONESTLY VERY HAPYYY TO FOUND THIS TUTORIAL
    PLEASE CARRY ON

    ReplyDelete
  72. Dear 9 Lesson Team + Srivina, u dnt know, how much i m getting pleasure to found this tutorial is very excellent an dbest for me. i spend 4 to5 days to learn .htaccess but not got result to apply. by chance i got your this tutorial link on google
    .htaccess tutorial with demo. i have no any word to say Thanks, but i will just say. 9Lesson is very excellent an dgoood on internet

    Cheeeers

    ReplyDelete
  73. Hi ! Very good tutorial - but i still problem with unicode in this part
    $urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
    how can i use russian characters for link name ?

    Thanx in advance !

    ReplyDelete
  74. hi i have seen u r tutorial it is very helpful for me,but in u r tutorial it is working for only page ,i need to working for multiple seo friendly urls .

    ReplyDelete
  75. i m first going to publish page and in insert the title and body then i have write those nto url then it give me page 404 . error

    ReplyDelete
  76. Notice: Undefined variable: blogurl in E:\xamp\htdocs\seo\publish.php on line 69 i am getting error..pls help me.

    ReplyDelete
  77. Will probably use this on my own site, i´ve noticed that friendly URLs is extremly important...

    ReplyDelete
  78. Thank you so much for wonderful post. It was really saves my time lot.

    ReplyDelete
  79. Thanks for your code..

    ReplyDelete
  80. by applying your tutorial,
    url is generating like this :
    http://localhost/nwr/article.php?url=2015/08/25/linkchange.html
    but i want url look like this :

    http://localhost/nwr/2015/08/25/linkchange.html

    so how can i do that.

    ReplyDelete
  81. by applying your tutorial,
    url is generating like this :
    http://localhost/nwr/article.php?url=2015/08/25/linkchange.html
    but i want url look like this :

    http://localhost/nwr/2015/08/25/linkchange.html

    so how can i do that.

    ReplyDelete
    Replies
    1. Apply .htaccess

      RewriteEngine On

      RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
      RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1

      Delete
    2. Not Working for the 2 links try for other link with url type
      ie: article.php?url=12
      profile.php?p_url=20

      try this, will not work for this please solve this one..

      Delete
  82. why i use all language supported...please help...sir

    ReplyDelete
  83. This comment has been removed by the author.

    ReplyDelete
  84. in my case for one page it is working properly.i:e(profile.php?view=anup);
    But if there are two different files and different functions like:
    (1) profile.php?view=anup --------------> This is one file.
    In this case i can n't be able to use the .htaccess the forst function is working
    (2) state.php?statename=odisha ---------> The Other One.
    If i write like this in .htaccess file
    RewriteRule ^([a-zA-Z0-9-/]+).html$ profile.php?view=$1
    RewriteRule ^([a-zA-Z0-9-/]+).html$ state.php?statename=$1

    ReplyDelete
  85. RewriteRule ^([a-zA-Z0-9_-]+)$ state.php?state_name=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/$ state.php?state_name=$1

    RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user_id=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user_id=$1

    state.php?state_name=odisha
    profile.php?user_id=07
    For Single Link its working fine but in this case .htaccess is not working infact showing some error...
    can anyone suggest me here, its necessary.. please reply ASAP.....

    ReplyDelete

mailxengine Youtueb channel
Make in India
X