使用 CodeIgniter 的 URL 中的加密参数


Encrypted parameter in URL using CodeIgniter

嗨,我正在使用CodeIgniter制作一个应用程序。

我想将数字 ID 加密为加密字符串。

http://example.com/post/6

http://example.com/post/v4th54u654khi3f23of23ir2h398eh2xi012

我尝试了内置的加密库

$this->加密->编码(6)

但它为每个页面加载生成不同的加密字符串,这不是我想要的,我想要永久链接,就像 Youtube 视频 ID 一样。

我需要加密的字符串也是可解密的。

您是否在配置文件中设置了$config['encryption_key'] = "Test@123";

你必须在字符串之后传递密钥

$this->encrypt->encode(6, 'Test@123')

$this->encrypt->decode(6, 'Test@123')

我为此扩展了核心库

创建文件名MY_Encrypt.php并将此文件放在应用程序''库中

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Encrypt extends CI_Encrypt
{
  function encode($string, $key = "", $url_safe = TRUE) {
      $ret = parent::encode($string, $key);
      if ($url_safe) {
          $ret = strtr($ret, array('+' => '.', '=' => '-', '/' => '~'));
      }
      return $ret;
  }
  function decode($string, $key = "") {
      $string = strtr($string, array('.' => '+', '-' => '=', '~' => '/'));
      return parent::decode($string, $key);
  } 
}  
?>

现在您可以使用

$this->encrypt->encode(6)

$this->encrypt->decode(6)

这将产生相同的结果。

Codeigniter 为此提供了一个库,您可以添加 autoload.php 文件您可以使用以下行进行编码和解码。可能是您将多次编码相同的值,例如"$a",然后编码值$encodedA不同,但是当您进行解码时,您将始终得到$decodedA= 123。 $a = '123';$encodedA = $this->encrypt->encode($a);$decodedA = $this->encrypt->decode($encodedA);

最简单的方法是:

要编码:$url_val=base64_encode($this->encryption->encrypt($var_to_encode));

解码:$var_to_encode=$this->encryption->decrypt(base64_decode($url_val));

测试功能

function test() {
    for($i=7000;$i<8000;$i++){
        $x=urlencode($this->encryption->encrypt($i));
        $y=$this->encryption->decrypt(urldecode($x));
        if ($y == $i) { //$y != $i cross test
            echo "$y&ltbr&gt;$x&ltbr&gt;&ltbr&gt;";
        }
    }
}

Cosidering config/config.php 有 fallwowing set:

$config['encryption_key'] ="key_here"

$config['permitted_uri_chars'] =  'a-z 0-9~%.:_'-'+=';

用于生成加密 id,就像 Youtube 观看 ID 一样我使用Hashids Spark for CodeIgniter

https://github.com/sekati/codeigniter-hashids

此帮助程序的目的是实现 Hashids 以从数字生成哈希(如 YouTube 或 Bitly)以混淆数据库 ID。

安装就像在说明中一样,我修改了第 20 行的hashids_helper.php

require_once FCPATH . 'sparks/sk-hashids/' . HASHIDS_VERSION . '/vendor/Hashids.php';

require_once FCPATH . 'vendor/Hashids.php';  //according to your Hashids path
<</div> div class="answers">

与其尝试编码和解码,不如将 id 隐藏为 SHA1。 sha1 将生成字母数字键,因此您也不会收到 URL 支持错误。 无需编码-解码。 这将生成一个安全的加密代码。

$random_key = sha1($leadDetails->lead_number);

对于那些如何在这里和库由于mycrpt ->而无法在php 7上运行的人新库:https://www.codeigniter.com/user_guide/libraries/encryption.html