Using Primary Key / ID Field as an identifier in a URL

前端 未结 6 1341
广开言路
广开言路 2020-12-28 09:56

What are the pros and cons of using your databases primary key as a URL identifier? As an example, http://localhost/post/view/13 - 13 being my primary key for my posts tabl

6条回答
  •  别那么骄傲
    2020-12-28 10:10

    You always want to present the user with a nice URL-not some nasty auto-generated ID. But I dont think you should make said "friendly url" the primary key. You should still use a "classic" auto-incremented, numeric PK and have a second column that is a unique "friendly url". Why?

    1. All the comment tables, ratings tables, whatever tables that have a relationship with your content table can use the numeric primary key. This means smaller indexes and lower memory use.
    2. Somebody will want to change the friendly url. If you've got a numeric primary key, you don't have to update any of your dependent tables (or have the DB do it via a cascading update).
    3. In the future, you can abstract out the URL bits into another table. Said table can then store "legacy" URL mappings that issue redirects to the primary "real" URL map. Then when the user wants to change the friendly URL, you don't have to break the all the inbound legacy URL's. Couldn't do this if your primary key was the "friendly URL".
    4. I'd still be inclined to use the numeric primary key in all my AJAX goo (for example, a post_new_comment() javascript function would take the primary key, not some friendly URL). The only time I'd use the friendly URL is in any user-facing URL structure.
    5. As for security? If your content is access controlled, you are gonna have to check access no matter if it is the primary key or some friendly URL.
    6. If you allow ways to get to the content via the primary key, people might try plugging in random ID's. If your requirement for not only limited access to content, but the denial said content exists, it is a matter of the phrasing of your errors. It is the same as with login failures--you dont say "username not found" you say "bad username or password". Plugging in random values to find content is gonna be a problem for any approach you take, it is just that with numeric keys there is way fewer values to try.

    Bottom line: Friendly URL's? Hell yeah. Using them as the primary key? Hell no.

提交回复
热议问题