Oj Obasi
Oj Obasi

I am also and will continue to be a student of web design and development. My tutorials may not be for you. If you feel that way, then search online for better tutorials.

How to make a seo friendly url using php and .htaccess

In this tutorial, I will show you how to can make your seo friendly website using php and .htaccess

he above two urls are of the same page. However, the second is seo friendly and that's what we want to learn to achieve here.

To achieve this , we will use a single including php file called urlseo.php and add some code to our .htaccess file

Here is the urlseo.php code:

function slug($string, $spaceRepl = "-") {
// Replace "&" char with "and"
$string = str_replace("&", "and", $string);
// Delete any chars but letters, numbers, spaces and _, -
$string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);
// Optional: Make the string lowercase
$string = strtolower($string);
// Optional: Delete double spaces
$string = preg_replace("/[ ]+/", " ", $string);
// Replace spaces with replacement
$string = str_replace(" ", $spaceRepl, $string);
return $string;
}
?>

In our .htaccess file, you need to add the following lines of code:

RewriteEngine On
RewriteRule ^tutorial/([0-9]+)/([a-zA-Z0-9_-]+) tutorial.php?id=$1

How do we apply this to work?
Lets say you are using a database to retrieve your data.I will show you an example mysqli database select statement to help us understand better how we can achieve our seo friendly url:

Mysqli Select in the page you want the seo friendly url
//WHILE LOOP for getting the blog data
$sql_file = "SELECT * FROM tu_rail ORDER BY post_date DESC";
$query_file = mysqli_query($conx, $sql_file);
$tutorials ='';
while($row = mysqli_fetch_array($query_file)){
$tu_id = $row["id"];
$title = $row["title"];

you remember in our urlseo.php file function, we are replacing characters, removing spaces and so on from our $title string.

$string = slug ($title);

//WHILE LOOP for getting the blog data
$sql_file = "SELECT * FROM mytable";
$query_file = mysqli_query($conx, $sql_file);
$blog ='';
while($row = mysqli_fetch_array($query_file)){
$tu_id = $row["id"];
$title = $row["title"];
$string = slug ($title);
$blog .='<a href="http://www.simplecss3.com/tutorial/'.$tu_id.'/'.$string.'">'.$title.'</a>';

You can now echo your $blog variable links anywhere in your main page and when clicked , you get your nice seo friendly url.