Home » Php » php – How do Stack Overflow URLs work?

php – How do Stack Overflow URLs work?

Posted by: admin July 12, 2020 Leave a comment


I have build URLs of my site like Stack Overflow URLs. My URLs are as below.


In this URL, 1255544 is the id and this-is-the-url-text is the URL title text, both stored in the database. I have noticed that Stack Overflow URLs work on the base of id. Suppose here is a Stack Overflow URL


In this URL, 15679171 is the id of the post. When I changed this id to 15706581 without touching the new-way-to-prevent-xss-attacks and pressed Enter, the URL automatically changed to the following URL:


And when I tried to remove some of the part of the URL title text like below


It automatically corrects the URL as below:


It means the data is being retrieved from the database on the basis of id 15679171 and the relevant URL title text, new-way-to-prevent-xss-attacks, is attached according to the id.

I also want to do this. But the problem is, I am not going to understand that if someone change the id of the URL the title text should automatically changed. How do I do this?

I have thought the following:

$url_id = $_GET["id"];
$url_txt = $_GET["url_txt"];

$qry = "SELECT * FROM mytable WHERE url_id = '{$url_id}' LIMIT 1";
$data = mysql_query($qry);
$data_set = mysql_fetch_array($data);

if($url_txt== $data_set["url_txt"]) {
    // proceed further
} else {
     $rebuilt_url = "http://www.example.com/" . $url_id . "/" . $data_set["url_txt"];
     header("Location: {$rebuilt_url}")  // Redirect to this URL

Is it the proper and efficient way to perform this action or not? Is there a solution?

How to&Answers:

Your code looks pretty good and in one of my Stack Overflow answers I had also suggested similar approach. However, I suggest just one minor improvement. Instead of:

header("Location: {$rebuilt_url}");

You should do:

header ('HTTP/1.1 301 Moved Permanently');
header("Location: {$rebuilt_url}");

This will let browser cache these URLs aggressively and you code and SQL queries will not be executed every time.

Also check:

  1. .htaccess if URL is bad do something
  2. .htaccess rewrite friendly URLs


If you use Apache, I think you must know about URL rewriting

In URL rewriting you rewrite the URL to a more friendly look. Take a look at the URL below


and when you do a URL rewrite on it, it became like this


URL rewriting needs to be set on the Apache configuration (rewriting rules) so it will rewrite your URL before request is interpret by PHP so you will get the exact resource you want to acquire

 RewriteRule ^/category$ /content.php  
  RewriteRule ^/category/([0-9]+)$ /.php?id=$1  

Well, I can’t explain you everything here, but below I provide you some links where you can learn about URL rewriting.

This the best hack you can do to create friendly URLs!