Encrypt/Encoding an ID in URL string

别说谁变了你拦得住时间么 提交于 2019-11-30 14:47:32

Hiding the ID is obscurity, not security.

If you want good obscurity, look at the mcrypt functions in PHP. Make sure to append a salt before encoding and decoding, otherwise it will be easy to guess the encryption/decryption.

And be aware that anyone else might still stumble across your URLs, defeating this entirely. I'd use some form of HTTP Auth over HTTPS if you want security, too.

A friend of mine implemented a method of signing all the GET requests with the current session token and a secret to prevent CSRF attacks.

But what you are trying to do is to have an URL that you can share with other people.

You could create an MD5 hash that resembles the original url, and save both in the database.

Now when /share/someLongId is opened, you can check in the database where to which URL that hash belongs and can redirect the user to that URL.

Another possibility is to use GUIDs instead of auto-incrementing IDs in the first place. That way all the IDs are just longer and not that easy to guess.

Depending on if you need it (the URL) to be persistent or not, you cold do either:

non-persistent: do something like this:

function getLink($id) {
   $random = md5(uniqid());
   $_SESSION['links'][$random] = $id;
   return "http://localhost/share/$random";
}
echo getLink(10);

and then:

function getTrueId($id) {
  if(isset($_SESSION['links'][$id]) {
     return $_SESSION['links'][$id];
  } else {
     die("Unknown link!");
  }

}

This will make links usable only to the current user in current session. If you need it persistent, you can generate random IDs and store them in the database along with real IDs, but this may be pointless, as the random ID can be used instead of real ID to do the same things...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!