Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create friendly URL in php?

Normally, the practice or very old way of displaying some profile page is like this:

www.domain.com/profile.php?u=12345 

where u=12345 is the user id.

In recent years, I found some website with very nice urls like:

www.domain.com/profile/12345 

How do I do this in PHP?

Just as a wild guess, is it something to do with the .htaccess file? Can you give me more tips or some sample code on how to write the .htaccess file?

like image 237
Peter Avatar asked May 01 '09 18:05

Peter


People also ask

How can I get SEO friendly URL in PHP?

The generateSeoURL() function automatically creates SEO friendly URL slug from the string using PHP. A title string needs to be passed as input and it returns a human-friendly URL string with a hyphen ( - ) as the word separator. $string – Required. The string which you want to convert to the SEO friendly URL.

What is a friendly URL example?

The benefit of creating a friendly URL is that they are easier to remember and contain key words about the web page. Example: Original URL: https://portal.ct.gov/Services/Education/Higher-Education/Higher-Education-Information-and-Resources. Friendly URL: https://portal.ct.gov/SDE-HigherEd.

How customize URL in PHP?

One way is to use the RewriteRule techniques mentioned earlier to mask query string values. One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].


1 Answers

According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:

RewriteEngine on RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1 

And this maps requests from

/news.php?news_id=63 

to

/news/63.html 

Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:

<Files news>     ForceType application/x-httpd-php </Files> 

And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:

<?php     echo $_SERVER['PATH_INFO'];     // outputs '/63.html' ?> 
like image 182
cgp Avatar answered Sep 21 '22 06:09

cgp