How to match a (large) integer (small size (alphanumeric string with PHP? (Cantor?)

I can’t figure out how to optimally do the following in PHP: In the database, I have messages with a unique identifier, for example, 19041985. Now I want to refer to these messages in a short url service, but not to use the generated hashes, but simply " compute "source identifier.

In other words, for example: http: //short.url/sYsn7 should allow me to calculate the message identifier that the visitor would like to request.

To make this more obvious, I wrote the following in PHP to generate these alphanumeric identification versions, and of course, another way will allow me to calculate the original message identifier.

Question: Is this the best way to do this? I don’t think so, but I can’t think of anything else.

$alphanumString = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
for($i=0;$i < strlen($alphanumString);$i++)
{
 $alphanumArray[$i] = substr($alphanumString,$i,1);
}



$id = 19041985;

$out = '';
for($i=0;$i < strlen($id);$i++) {

 if(isset($alphanumString["".substr($id,$i,2).""]) && strlen($alphanumString["".substr($id,$i,2).""]) > 0) {
  $out.=$alphanumString["".substr($id,$i,2).""];
 } else {
  $out.=$alphanumString["".substr($id,$i,1).""];
  $out.=$alphanumString["".substr($id,($i+1),1).""];
 }
 $i++;
}

print $out;
+3
source share
2 answers
echo trim(base64_encode(pack("L", 19041987)), "=");
print_r(unpack("L", base64_decode("w44iAQ")));
  • The packet changes the number by four bytes, which is very short, but unreadable.
  • Base64_encode changes four bytes to several human-readable characters.
  • He adds some characters that are not needed.

If you use base64_encode (19041987), you get the encoding for the string "19041987", which is not shorter.

+1
source

You should never use a function inside a for statement, as it plays during each loop.

For example your

for($i=0;$i < strlen($alphanumString);$i++)
{
 $alphanumArray[$i] = substr($alphanumString,$i,1);
}

it should be

var $alphaLength = strlen($alphanumString);
for($i=0;$i < $alphaLength;$i++)
{
 $alphanumArray[$i] = substr($alphanumString,$i,1);
}
-1
source

Source: https://habr.com/ru/post/1749005/


All Articles