简体   繁体   中英

how to rewrite the url in php with dynamic names based on id in the url

how To make url for as seo friendly. Now the link is like http://www.example.com/memorial.php?id=354

We want it to be http://www.example.com/firstname-middlename-lastname

so here first,last,and middle names from db based on id.

thanks in advance.

You can select details from Db then You can use header("Location: http://www.example.com/firstname-middlename-lastname "); /* Redirect browser */ to redirect

Approach to work with this -

  1. Add the slug coloumn in your table
  2. Give option to add slug to user or create slug dynamically and insert it into the table.
  3. Write the ReWriteRule to understand the request

Example:- Is given to add dynamic slug.

1.User Table Schema is like -

+----------------+---------------------+------+-----+---------+----------------+
| Field          | Type                | Null | Key | Default | Extra          |
+----------------+---------------------+------+-----+---------+----------------+
| user_id        | int(11)             | NO   | PRI | NULL    | auto_increment |
| first_name     | varchar(255)        | YES  |     | NULL    |                |
| middle_name    | varchar(255)        | YES  |     | NULL    |                |
| last_name      | varchar(255)        | YES  |     | NULL    |                |
| slug           | varchar(255)        | NO   |     | 0       |                |
+----------------+---------------------+------+-----+---------+----------------+
  1. Before inserting user information into the User table use regular expression to support dnyamic seo slug-

     function seo_str_replace($str){ $str = preg_replace("/^[^a-z0-9]+/", "", $str); $str = preg_replace("/[^a-z0-9]+$/", "", $str); $str = preg_replace("/[^a-z0-9]/", "-", $str); return $str; } $first_name = $_POST['first_name']; $middle_name = $_POST['middle_name']; $last_name = $_POST['last_name']; $slugArr = Array(); if(!empty($first_name)){ $slugArr[] = $first_name; } if(!empty($middle_name)){ $slugArr[] = $middle_name; } if(!empty($last_name)){ $slugArr[] = $last_name; } $slug = seo_str_replace(implode('-',$slugArr); 
  2. Insert slug into the table "User"

     $sql = "insert into user(first_name,middle_name,last_name,slug)values('$first_name','$middle_name','$last_name','$slug')"; 
  3. To get the slug you have to use rewrite rule for url http://www.example.com/memorial/firstname-middlename-lastname -

     RewriteRule ^/memorial/(.*)$ /memorial.php?slug=$1 
  4. On memorial.php get the slug & search it into the table.

      $slug = $_GET['slug']; $sql= "select user_id from User where slug = '".$slug."'"; <!---- here Start your code ---> 

Note: Don't forgot to add index on slug column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM