繁体   English   中英

使用 php 编码和解码 url 消息 ID

[英]Encode and decode url message ID using php

我正在尝试对 php 应用程序的消息 ID 进行编码,但我找不到有关如何执行此操作的明确描述。

基本上我有一个 url 例如 - http://www.mymessager.com?messageID=1234

I want to have the system encode the message id for the url but do not change it in the database, for example - http://www.mymessager.com?messageID=38927648726894762345768

How can I do such a thing so that if someone goes to the encoded url the php will display http://www.mymessager.com?messageID=38927648726894762345768 in the address bar, but the script will pull message 1234 out of the database?

我知道那里有类似的问题,但我还没有找到一个谈论我想做的事情(主要是清理 url)。

这是为了避免其他用户打开其他用户的messageID=4321等私信吗? 因为那样的话,这条路是走不通的!

您应该检查打开消息的用户是否真的被允许这样做。

如果消息是非私密的,并且您只是不希望人们通过修改数字来逐步查看消息。 然后,您可以向数据库添加一个“messageKey”字段并设置指定长度的随机字符串。 示例http://www.mymessager.com?messageKey=jadg23sf34lhs

现在只需在数据库中搜索带有该 messageKey 的消息。 请记住确保 messageKey 是唯一的。

通过这种方式,您还可以将 messageKey 设置为易于记忆的内容,或者可能对 SEO 友好。 只要是独一无二的。

我实际上将它们翻译成一个字符串:

$consts = array(66016,57721, 42344,56714,76422);
define( 'BASE', 36 );
$to_encrypt = 5789;
// Generate a random seed value as an index of the constants
$seed = rand(0,count()-1);

// Add the constant the product of the seed and the to the value to be encrypted 
// (the multiplication just serves to create more noise)
$base_crypt = ( $consts[ $seed ] + $to_encrypt * ( $seed + 1 ) );

//SEE NOTES ON FLOATING POINT ISSUES IN PHP DOCS!
$encrypted = base_convert( BASE * $base_crypt + $seed, 10, BASE );

然后解密:

 $encrypted = base_convert( $_GET[ 'encrypted' ], BASE, 10 );
 $seed      = $encrypted % BASE;
 $decrypted = ( ( $encrypted - $seed )/BASE - $consts[ $seed ])/( $seed + 1 );

您可能需要在一定程度上使用bcadd等,但我有这个系统的生产副本并且它可以工作。

(我必须包含一个指向我首次发布此内容的链接)。

如果您正在散列(例如使用 md5)该值,您可以比较 id 的散列值,例如:

   $SQL = "SELECT * FROM `messages` WHERE MD5(ID) = '".$_GET['id']."'";

这通常通过为数据库中的每个条目存储另一个 ID 来完成。 如果您不想使用 go 这条路线,则必须使用可以与“公共”ID 相互转换的 function。 喜欢...

function toPublicId($id) {
  return $id * 1498158 + 825920496;
}

function toInternalId($publicId) {
  return ($publicId - 825920496) / 1498158;
}

管他呢。 我有时使用有保证的唯一字母数字 ID 作为公共 ID,通过转换到/从例如 base36 和一个大的乘数 + 偏移量来转换到/从它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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