分类 PHP 下的文章

NanoID - 轻量、安全的 Unique ID 生成器

NanoID

一个小巧、安全、URL友好、唯一的 JavaScript 字符串 ID 生成器。

  • 小巧:130 bytes (已压缩和 gzipped), 没有依赖,Size Limit 控制大小;
  • 快速:它比 UUID 快 60%;
  • 安全:它使用加密的强随机 API,可在集群中使用;
  • 紧凑:它使用比 UUID(A-Za-z0-9_-)更大的字母表,因此,ID 大小从 36 个符号减少到 21 个符号;
  • 易用:Nano ID 已被移植到 20种编程语言。
php版:https://github.com/hidehalo/nanoid-php

- 阅读剩余部分 -

Nginx部署ThinkPHP时报错500问题

nginx配置文件fastcgi.conf
找到fastcgi_param PHP_ADMIN_VALUE这个参数,在这个参数的字符串中加入路径

fastcgi_param PHP_ADMIN_VALUE "open_basedir=$document_root/:/tmp/:/proc/:/mnt/hgfs/phpworkspace/:站点部署路径";

php国密sm4加解密

国密算法sm4对应的php加解密代码

<?php
Class SM4Util
{
    const SM4_CK = [
        0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
        0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
        0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
        0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
        0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
        0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
        0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
        0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279
    ];

    const SM4_Sbox = [
        0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
        0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
        0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
        0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
        0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
        0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
        0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
        0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
        0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
        0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
        0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
        0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
        0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
        0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
        0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
        0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48
    ];

    /**
     * 系统参数
     */
    const SM4_FK = [0xA3B1BAC6, 0x56AA3350, 0x677D9197, 0xB27022DC];

    private $key = [];//16个 HEXHEX格式的数组 16字节 128bits  为了操作方便,直接存成十进制

    private $skey = [];//记录每轮加密的秘钥 记录成十进制

    private $block_size = 32;

    /**
     * 字符串转16进制
     * @param $str
     * @return string
     */
    public function strToHex($string){
        $hex="";
        for($i=0;$i<strlen($string);$i++)
            $hex.=dechex(ord($string[$i]));
        $hex=strtoupper($hex);
        if(strlen($hex)>32){
            return substr($hex,0,32);
        }else{
            return $hex;
        }
    }


    /**设置加密秘钥
     *
     * @param $key 32个十六进制的字符
     *
     * @return $this
     * @throws Exception
     */
    public function setKey($key)
    {
        $key = $this->strToHex($key);

        $this->key = $this->preProcess($key);
        $this->setSkey();

        return $this;
    }

    /**
     * 计算每轮加密需要的秘钥
     */
    private function setSkey()
    {
        $skey = [];
        for ($i = 0; $i < 4; $i++) {
            $skey[] = self::SM4_FK[$i] ^ ($this->key[4 * $i] << 24 | $this->key[4 * $i + 1] << 16 | $this->key[4 * $i + 2] << 8 | $this->key[4 * $i + 3]);
        }
        for ($k = 0; $k < 32; $k++) {
            $tmp = $skey[$k + 1] ^ $skey[$k + 2] ^ $skey[$k + 3] ^ self::SM4_CK[$k];

            //非线性化操作
            $buf = (self::SM4_Sbox[($tmp >> 24) & 0xff]) << 24 |
                (self::SM4_Sbox[($tmp >> 16) & 0xff]) << 16 |
                (self::SM4_Sbox[($tmp >> 8) & 0xff]) << 8 |
                (self::SM4_Sbox[$tmp & 0xff]);
            //线性化操作
            $skey[] = $skey[$k] ^ ($buf ^ $this->sm4Rotl32($buf, 13) ^ $this->sm4Rotl32($buf, 23));
            $this->skey[] = $skey[$k + 4];
        }
    }


    /**32比特的buffer中循环左移n位
     *
     * @param $buf int 可以传递进10进制 也可以是0b开头的二进制
     * @param $n int 向左偏移n位
     *
     * @return int
     * reference http://blog.csdn.net/w845695652/article/details/6522285
     */
    private function sm4Rotl32($buf, $n)
    {
        return (($buf << $n) & 0xffffffff) | ($buf >> (32 - $n));
    }

    /**
     * 对字符串加密
     *
     * @param $plainText
     *
     * @return string
     * @throws Exception
     */
    public function encryptData($plainText)
    {
        $bytes = bin2hex($plainText);

        $need_pad_length = $this->block_size - strlen($bytes) % $this->block_size;
        $pad_bytes = str_pad(
            $bytes,
            strlen($bytes) + $need_pad_length,
            sprintf("%02x", $need_pad_length / 2),
            STR_PAD_RIGHT
        );
        $chunks = str_split($pad_bytes, $this->block_size);

        return strtolower(implode('', array_map(function ($chunk) {
            return $this->encrypt($chunk);
        }, $chunks)));
    }


    /**SM4加密单个片段(128bit)
     *
     * @param $text string 32个十六进制字符串
     *
     * @return string
     * @throws Exception
     */
    public function encrypt($text)
    {
        $x = $re = [];
        $t = $this->preProcess($text);


        for ($i = 0; $i < 4; $i++) {
            $x[] = $t[$i * 4] << 24 |
                $t[$i * 4 + 1] << 16 |
                $t[$i * 4 + 2] << 8 |
                $t[$i * 4 + 3];
        }

        for ($k = 0; $k < 32; $k++) {
            $tmp = $x[$k + 1] ^ $x[$k + 2] ^ $x[$k + 3] ^ $this->skey[$k];

            $buf = self::SM4_Sbox[($tmp >> 24) & 0xff] << 24 |
                self::SM4_Sbox[($tmp >> 16) & 0xff] << 16 |
                self::SM4_Sbox[($tmp >> 8) & 0xff] << 8 |
                self::SM4_Sbox[$tmp & 0xff];

            $x[$k + 4] = $x[$k] ^ $buf
                ^ $this->sm4Rotl32($buf, 2)
                ^ $this->sm4Rotl32($buf, 10)
                ^ $this->sm4Rotl32($buf, 18)
                ^ $this->sm4Rotl32($buf, 24);
        }
        for ($i = 0; $i < 4; $i++) {
            $re[] = ($x[35 - $i] >> 24) & 0xff;
            $re[] = ($x[35 - $i] >> 16) & 0xff;
            $re[] = ($x[35 - $i] >> 8) & 0xff;
            $re[] = $x[35 - $i] & 0xff;
        }

        return $this->wrapResult($re);

    }


    /**预处理16字节长度的16进制字符串 返回10进制的数组 数组大小为16
     *
     * @param $text
     *
     * @return array
     * @throws Exception
     */
    private function preProcess($text)
    {
        preg_match('/[0-9a-f]{32}/', strtolower($text), $re);
        if (empty($re)) {
            throw new Exception('error input format!');
        }
        $key = $re[0];
        for ($i = 0; $i < 16; $i++) {
            $result[] = hexdec($key[2 * $i] . $key[2 * $i + 1]);
        }

        return $result;
    }

    /**将十进制结果包装成16进制字符串输出
     *
     * @param $result
     *
     * @return string
     */
    private function wrapResult($result)
    {
        $hex_str = '';
        foreach ($result as $v) {
            $tmp = dechex($v);
            $len = strlen($tmp);
            if ($len == 1)//不足两位十六进制的数 在前面补一个0,保证输出也是32个16进制字符
            {
                $hex_str .= '0';
            }
            $hex_str .= $tmp;
        }

        return strtoupper($hex_str);
    }


    /**SM4解密单个片段(128bits)
     *
     * @param $text string 32个16进制字符串
     *
     * @return string
     * @throws Exception
     */
    public function decrypt($text)
    {
        $x = $re = [];
        $t = $this->preProcess($text);
        for ($i = 0; $i < 4; $i++) {
            $x[] = $t[4 * $i] << 24 |
                $t[4 * $i + 1] << 16 |
                $t[4 * $i + 2] << 8 |
                $t[4 * $i + 3];
        }
        for ($k = 0; $k < 32; $k++) {
            $tmp = $x[$k + 1] ^ $x[$k + 2] ^ $x[$k + 3] ^ $this->skey[31 - $k];
            $buf = (self::SM4_Sbox[($tmp >> 24) & 0xff]) << 24 |
                (self::SM4_Sbox[($tmp >> 16) & 0xff]) << 16 |
                (self::SM4_Sbox[($tmp >> 8) & 0xff]) << 8 |
                (self::SM4_Sbox[$tmp & 0xff]);
            $x[$k + 4] = $x[$k] ^ $buf
                ^ $this->sm4Rotl32($buf, 2)
                ^ $this->sm4Rotl32($buf, 10)
                ^ $this->sm4Rotl32($buf, 18)
                ^ $this->sm4Rotl32($buf, 24);
        }

        for ($i = 0; $i < 4; $i++) {
            $re[] = ($x[35 - $i] >> 24) & 0xff;
            $re[] = ($x[35 - $i] >> 16) & 0xff;
            $re[] = ($x[35 - $i] >> 8) & 0xff;
            $re[] = $x[35 - $i] & 0xff;
        }

        return $this->wrapResult($re);
    }

    public function decryptData($cipherText)
    {
        $chunks = str_split($cipherText, $this->block_size);
        $decrypt_text_data = implode('', array_map(function ($chunk) {
            return $this->decrypt($chunk);
        }, $chunks));

        $pad_length = hexdec(substr($decrypt_text_data, -2));

        return strtolower(hex2bin(preg_replace(
            sprintf("/%s$/", str_repeat(sprintf("%02x", $pad_length), $pad_length)),
            '',
            $decrypt_text_data
        )));
    }


}

$data=[
    "DOC_ID"=>"",'STATE'=>"1"
];
$sm4 = new SM4Util();
$original_plain_text_data = json_encode($data,true);

$key = 'abcdefghij123456';

$origin_encrypted_text = '58fb892aef37be96fc032d0613d4aaea5cb416baa6aac04f304d02604bb4701c';
$encrypted_text_data = $sm4->setKey($key)->encryptData($original_plain_text_data);
echo '<br>';
echo"自己加密:".$encrypted_text_data;
echo '<br>长度:'.strlen($encrypted_text_data);
echo '<br>';
echo"自己解密:". $sm4->setKey($key)->decryptData($encrypted_text_data);

echo '<hr>';

echo"原文:".$origin_encrypted_text;
echo '<br>长度:'.strlen($origin_encrypted_text);
//$encrypted_text_2_plain_text = $sm4->setKey($key)->decryptData($encrypted_text_data);
$original_decrypted_text = $sm4->setKey($key)->decryptData($origin_encrypted_text);
echo '<br>';
echo "原文解密:".$original_decrypted_text ;
echo '<br>';

另一种方法(实际使用过程中未解密成功,暂未深究)

<?php
class SM4 {
    const SM4_CK = [
        0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
        0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
        0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
        0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
        0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
        0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
        0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
        0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279
    ];
    const SM4_SBOX = [
        0xd6,0x90,0xe9,0xfe,0xcc,0xe1,0x3d,0xb7,0x16,0xb6,0x14,0xc2,0x28,0xfb,0x2c,0x05,
        0x2b,0x67,0x9a,0x76,0x2a,0xbe,0x04,0xc3,0xaa,0x44,0x13,0x26,0x49,0x86,0x06,0x99,
        0x9c,0x42,0x50,0xf4,0x91,0xef,0x98,0x7a,0x33,0x54,0x0b,0x43,0xed,0xcf,0xac,0x62,
        0xe4,0xb3,0x1c,0xa9,0xc9,0x08,0xe8,0x95,0x80,0xdf,0x94,0xfa,0x75,0x8f,0x3f,0xa6,
        0x47,0x07,0xa7,0xfc,0xf3,0x73,0x17,0xba,0x83,0x59,0x3c,0x19,0xe6,0x85,0x4f,0xa8,
        0x68,0x6b,0x81,0xb2,0x71,0x64,0xda,0x8b,0xf8,0xeb,0x0f,0x4b,0x70,0x56,0x9d,0x35,
        0x1e,0x24,0x0e,0x5e,0x63,0x58,0xd1,0xa2,0x25,0x22,0x7c,0x3b,0x01,0x21,0x78,0x87,
        0xd4,0x00,0x46,0x57,0x9f,0xd3,0x27,0x52,0x4c,0x36,0x02,0xe7,0xa0,0xc4,0xc8,0x9e,
        0xea,0xbf,0x8a,0xd2,0x40,0xc7,0x38,0xb5,0xa3,0xf7,0xf2,0xce,0xf9,0x61,0x15,0xa1,
        0xe0,0xae,0x5d,0xa4,0x9b,0x34,0x1a,0x55,0xad,0x93,0x32,0x30,0xf5,0x8c,0xb1,0xe3,
        0x1d,0xf6,0xe2,0x2e,0x82,0x66,0xca,0x60,0xc0,0x29,0x23,0xab,0x0d,0x53,0x4e,0x6f,
        0xd5,0xdb,0x37,0x45,0xde,0xfd,0x8e,0x2f,0x03,0xff,0x6a,0x72,0x6d,0x6c,0x5b,0x51,
        0x8d,0x1b,0xaf,0x92,0xbb,0xdd,0xbc,0x7f,0x11,0xd9,0x5c,0x41,0x1f,0x10,0x5a,0xd8,
        0x0a,0xc1,0x31,0x88,0xa5,0xcd,0x7b,0xbd,0x2d,0x74,0xd0,0x12,0xb8,0xe5,0xb4,0xb0,
        0x89,0x69,0x97,0x4a,0x0c,0x96,0x77,0x7e,0x65,0xb9,0xf1,0x09,0xc5,0x6e,0xc6,0x84,
        0x18,0xf0,0x7d,0xec,0x3a,0xdc,0x4d,0x20,0x79,0xee,0x5f,0x3e,0xd7,0xcb,0x39,0x48
    ];
    const SM4_FK = [0xA3B1BAC6, 0x56AA3350, 0x677D9197, 0xB27022DC];

    public $_rk = [];
    public $_block_size = 16;

    public function __construct()
    {
    }

    public function encrypt($key, $data)
    {
        $this->sM4KeySchedule($key);
        $bytes = $this->pad($data, $this->_block_size);
        $chunks = array_chunk($bytes, $this->_block_size);
        $ciphertext = "";
        foreach ($chunks as $chunk) {
            $ciphertext .= $this->sM4Encrypt($chunk);
        }
        return base64_encode($ciphertext);
    }
    public function decrypt($key, $data)
    {
        $data = base64_decode($data);
        if (strlen($data) < 0 || strlen($data) % $this->_block_size != 0) {
            return false;
        }
        $this->sM4KeySchedule($key);
        $bytes = unpack("C*", $data);
        $chunks = array_chunk($bytes, $this->_block_size);
        $plaintext = "";
        foreach ($chunks as $chunk) {
            $plaintext .= substr($this->sM4Decrypt($chunk), 0, 16);
        }
        $plaintext = $this->un_pad($plaintext);
        return $plaintext;
    }
    private function sM4Decrypt($cipherText)
    {
        $x = [];
        for ($j=0; $j<4; $j++) {
            $x[$j]=($cipherText[$j*4]<<24) |($cipherText[$j*4+1]<<16)| ($cipherText[$j*4+2]<<8)|($cipherText[$j*4+3]);
        }
        for ($i=0; $i<32; $i++) {
            $tmp = $x[$i+1]^$x[$i+2]^$x[$i+3]^$this->_rk[31-$i];
            $buf= (self::SM4_SBOX[($tmp >> 24) & 0xFF]) << 24 |(self::SM4_SBOX[($tmp >> 16) & 0xFF]) << 16 |(self::SM4_SBOX[($tmp >> 8) & 0xFF]) << 8 |(self::SM4_SBOX[$tmp & 0xFF]);
            $x[$i+4]=$x[$i]^($buf^$this->sm4Rotl32(($buf), 2)^ $this->sm4Rotl32(($buf), 10) ^ $this->sm4Rotl32(($buf), 18)^ $this->sm4Rotl32(($buf), 24));
        }
        $plainText = [];
        for ($k=0; $k<4; $k++) {
            $plainText[4*$k]=($x[35-$k]>> 24)& 0xFF;
            $plainText[4*$k+1]=($x[35-$k]>> 16)& 0xFF;
            $plainText[4*$k+2]=($x[35-$k]>> 8)& 0xFF;
            $plainText[4*$k+3]=($x[35-$k])& 0xFF;
        }
        return $this->bytesToString($plainText);
    }
    private function sM4Encrypt($plainText)
    {
        $x = [];
        for ($j=0; $j<4; $j++) {
            $x[$j]=($plainText[$j*4]<<24) |($plainText[$j*4+1]<<16)| ($plainText[$j*4+2]<<8)|($plainText[$j*4+3]);
        }
        for ($i=0; $i<32; $i++) {
            $tmp = $x[$i+1]^$x[$i+2]^$x[$i+3]^$this->_rk[$i];
            $buf= (self::SM4_SBOX[($tmp >> 24) & 0xFF]) << 24 |(self::SM4_SBOX[($tmp >> 16) & 0xFF]) << 16 |(self::SM4_SBOX[($tmp >> 8) & 0xFF]) << 8 |(self::SM4_SBOX[$tmp & 0xFF]);
            $x[$i+4]=$x[$i]^($buf^$this->sm4Rotl32(($buf), 2)^ $this->sm4Rotl32(($buf), 10) ^ $this->sm4Rotl32(($buf), 18)^ $this->sm4Rotl32(($buf), 24));
        }
        $cipherText = [];
        for ($k=0; $k<4; $k++) {
            $cipherText[4*$k]=($x[35-$k]>> 24)& 0xFF;
            $cipherText[4*$k+1]=($x[35-$k]>> 16)& 0xFF;
            $cipherText[4*$k+2]=($x[35-$k]>> 8)& 0xFF;
            $cipherText[4*$k+3]=($x[35-$k])& 0xFF;
        }
        return $this->bytesToString($cipherText);
    }
    private function stringToBytes($string)
    {
        return unpack('C*', $string);
    }
    private function bytesToString($bytes)
    {
        return vsprintf(str_repeat('%c', count($bytes)), $bytes);
    }
    private function pad($data)
    {
        $bytes = $this->stringToBytes($data);
        $rem = $this->_block_size - count($bytes) % $this->_block_size;
        for ($i = 0; $i < $rem; $i++) {
            array_push($bytes, $rem);
        }
        return $bytes;
    }
    private function un_pad($data)
    {
        $bytes = $this->stringToBytes($data);
        $rem = $bytes[count($bytes)];
        $bytes = array_slice($bytes, 0, count($bytes) - $rem);
        return $this->bytesToString($bytes);
    }
    private function sm4Rotl32($buf, $n)
    {
        return (($buf << $n) & 0xffffffff) | ($buf >> (32-$n));
    }
    private function sM4KeySchedule($key)
    {
        $this->_rk = [];
        $key = array_values(unpack("C*", $key));
        $k = [];
        for ($i=0; $i<4; $i++) {
            $k[$i] = self::SM4_FK[$i]^(($key[4*$i]<<24) | ($key[4*$i+1]<<16) |($key[4*$i+2]<<8) | ($key[4*$i+3]));
        }
        for ($j=0; $j<32; $j++) {
            $tmp = $k[$j+1]^$k[$j+2]^$k[$j+3]^ self::SM4_CK[$j];
            $buf = (self::SM4_SBOX[($tmp >> 24) & 0xFF]) << 24 |(self::SM4_SBOX[($tmp >> 16) & 0xFF]) << 16 |(self::SM4_SBOX[($tmp >> 8) & 0xFF]) << 8 |(self::SM4_SBOX[$tmp & 0xFF]);
            $k[$j+4]=$k[$j]^(($buf)^($this->sm4Rotl32(($buf), 13))^($this->sm4Rotl32(($buf), 23)));
            $this->_rk[$j]=$k[$j+4];
        }
    }
}
 
$key = base64_decode("E1Fg4vX90nFUmP7lmsg6FA==");//加密使用的key(字符串)
// $key = '1478523698563214';
$data = '中国加中国加油中国加油中国加油中国加油中国加油中国加油中国加油中国加油中国加油中国加油中国加油中国加油油';
$sm4 = new SM4();
echo "加密key:" . $key . "<br />";
echo "明文:" . $data . "<br />";
 
$a = $sm4->encrypt($key, $data);
echo "加密结果:" . $a . "<br />";
 
$b = $sm4->decrypt($key, $a);
echo "解密结果:" . $b . "<br />";

利用DatePeriod 类获取两个日期之间的所有日期

官方文档:https://www.php.net/manual/zh/class.dateperiod.php
DatePeriod 类表示一个时间周期,时间周期内允许对一组日期和时间进行迭代,在指定的时间间隔内定期重复。
注意:8.2 新增 DatePeriod::INCLUDE_END_DATE

/**
 * 获取两个日期间的所有日期
 * @param $startDate 2023-04-01
 * @param $endDate  2023-04-19
 * @param $format
 * @param $last 是否包含最后一天
 * @return array
 * @throws Exception
 */
function getDateRange($startDate, $endDate, $format = "Y-m-d", $last=true, $first=true)
{
    $begin = new DateTime($startDate);
    $end = new DateTime($endDate);
    if($last){
        $end->modify('+1 day');
    }
    $interval = new DateInterval('P1D'); // 1 Day
    $exclude = 0;
    if(!$first){
        $exclude = DatePeriod::EXCLUDE_START_DATE;
    }
    $dateRange = new DatePeriod($begin, $interval, $end, $exclude);
    $range = [];
    foreach ($dateRange as $date) {
        $range[] = $date->format($format);
    }
    return $range;
}

windows下php7.4安装imagick、ImageMagick、GhostScript实现pdf转图片

实现word转pdf->pdf转图片->对转换后的图片处理完成后再生成pdf功能。

php3.png

本地windows开发环境配置方式:

  1. 查看phpinfo确定需下载的imagick扩展类型,下载地址为:https://windows.php.net/downloads/pecl/releases/imagick 考虑到ImageMagick官网不支持历史版本下载,imagick扩展优先使用高版本,确保两者版本一致。

- 阅读剩余部分 -

php编译安装oci8 pdo_oci扩展

系统环境:centos7.8 + php7.4 + thinkphp6 + oracle 11g

注意:使用独立下载的扩展容易引起部分错误信息,不建议使用。推荐使用对应php版本中的ext扩展直接编译安装。

【安装oracle客户端】
下载地址
https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html

- 阅读剩余部分 -

PHP阳历转阴历(农历)类,支持生肖、时辰等老黄历

支持阳历阴历相互转换、获取生肖、时辰、节气等老黄历数据。(此接口初始代码来源网络,有待测试)

注:不支持闰年,如2023年

<?php
/**
 * Desc: 阳历/农历 转换
 * User: SenSen Wechat:1050575278
 * Date: 2021/9/4
 * Time: 10:42
 */

namespace sensen\services;

class LunarService
{
    static public $minYear = 1891;
    static public $maxYear = 2100;
    static public $lunarInfo = [
        [0,2,9,21936],[6,1,30,9656],[0,2,17,9584],[0,2,6,21168],[5,1,26,43344],[0,2,13,59728],[0,2,2,27296],[3,1,22,44368],[0,2,10,43856],[8,1,30,19304],[0,2,19,19168],[0,2,8,42352],[5,1,29,21096],[0,2,16,53856],[0,2,4,55632],[4,1,25,27304],[0,2,13,22176],[0,2,2,39632],[2,1,22,19176],[0,2,10,19168],[6,1,30,42200],[0,2,18,42192],[0,2,6,53840],[5,1,26,54568],[0,2,14,46400],[0,2,3,54944],[2,1,23,38608],[0,2,11,38320],[7,2,1,18872],[0,2,20,18800],[0,2,8,42160],[5,1,28,45656],[0,2,16,27216],[0,2,5,27968],[4,1,24,44456],[0,2,13,11104],[0,2,2,38256],[2,1,23,18808],[0,2,10,18800],[6,1,30,25776],[0,2,17,54432],[0,2,6,59984],[5,1,26,27976],[0,2,14,23248],[0,2,4,11104],[3,1,24,37744],[0,2,11,37600],[7,1,31,51560],[0,2,19,51536],[0,2,8,54432],[6,1,27,55888],[0,2,15,46416],[0,2,5,22176],[4,1,25,43736],[0,2,13,9680],[0,2,2,37584],[2,1,22,51544],[0,2,10,43344],[7,1,29,46248],[0,2,17,27808],[0,2,6,46416],[5,1,27,21928],[0,2,14,19872],[0,2,3,42416],[3,1,24,21176],[0,2,12,21168],[8,1,31,43344],[0,2,18,59728],[0,2,8,27296],[6,1,28,44368],[0,2,15,43856],[0,2,5,19296],[4,1,25,42352],[0,2,13,42352],[0,2,2,21088],[3,1,21,59696],[0,2,9,55632],[7,1,30,23208],[0,2,17,22176],[0,2,6,38608],[5,1,27,19176],[0,2,15,19152],[0,2,3,42192],[4,1,23,53864],[0,2,11,53840],[8,1,31,54568],[0,2,18,46400],[0,2,7,46752],[6,1,28,38608],[0,2,16,38320],[0,2,5,18864],[4,1,25,42168],[0,2,13,42160],[10,2,2,45656],[0,2,20,27216],[0,2,9,27968],[6,1,29,44448],[0,2,17,43872],[0,2,6,38256],[5,1,27,18808],[0,2,15,18800],[0,2,4,25776],[3,1,23,27216],[0,2,10,59984],[8,1,31,27432],[0,2,19,23232],[0,2,7,43872],[5,1,28,37736],[0,2,16,37600],[0,2,5,51552],[4,1,24,54440],[0,2,12,54432],[0,2,1,55888],[2,1,22,23208],[0,2,9,22176],[7,1,29,43736],[0,2,18,9680],[0,2,7,37584],[5,1,26,51544],[0,2,14,43344],[0,2,3,46240],[4,1,23,46416],[0,2,10,44368],[9,1,31,21928],[0,2,19,19360],[0,2,8,42416],[6,1,28,21176],[0,2,16,21168],[0,2,5,43312],[4,1,25,29864],[0,2,12,27296],[0,2,1,44368],[2,1,22,19880],[0,2,10,19296],[6,1,29,42352],[0,2,17,42208],[0,2,6,53856],[5,1,26,59696],[0,2,13,54576],[0,2,3,23200],[3,1,23,27472],[0,2,11,38608],[11,1,31,19176],[0,2,19,19152],[0,2,8,42192],[6,1,28,53848],[0,2,15,53840],[0,2,4,54560],[5,1,24,55968],[0,2,12,46496],[0,2,1,22224],[2,1,22,19160],[0,2,10,18864],[7,1,30,42168],[0,2,17,42160],[0,2,6,43600],[5,1,26,46376],[0,2,14,27936],[0,2,2,44448],[3,1,23,21936],[0,2,11,37744],[8,2,1,18808],[0,2,19,18800],[0,2,8,25776],[6,1,28,27216],[0,2,15,59984],[0,2,4,27424],[4,1,24,43872],[0,2,12,43744],[0,2,2,37600],[3,1,21,51568],[0,2,9,51552],[7,1,29,54440],[0,2,17,54432],[0,2,5,55888],[5,1,26,23208],[0,2,14,22176],[0,2,3,42704],[4,1,23,21224],[0,2,11,21200],[8,1,31,43352],[0,2,19,43344],[0,2,7,46240],[6,1,27,46416],[0,2,15,44368],[0,2,5,21920],[4,1,24,42448],[0,2,12,42416],[0,2,2,21168],[3,1,22,43320],[0,2,9,26928],[7,1,29,29336],[0,2,17,27296],[0,2,6,44368],[5,1,26,19880],[0,2,14,19296],[0,2,3,42352],[4,1,24,21104],[0,2,10,53856],[8,1,30,59696],[0,2,18,54560],[0,2,7,55968],[6,1,27,27472],[0,2,15,22224],[0,2,5,19168],[4,1,25,42216],[0,2,12,42192],[0,2,1,53584],[2,1,21,55592],[0,2,9,54560]
    ];

    /**
     * 阳历转阴历
     */
    public static function convertSolarToLunar($date='')
    {
        $date = $date?date('Y-n-j', strtotime($date)):date('Y-n-j');
        $dateArr = explode('-', $date);
        $yearIndex = $dateArr[0] - self::$minYear;
        $yearData = self::$lunarInfo[$yearIndex];

        if($dateArr[0] == self::$minYear && $dateArr[1]<=2 && $dateArr[2]<=9){
            $return = [1891, '正月', '初一', '辛卯', 1, 1, '兔'];
        }else{
            $return = self::getLunarByBetween($dateArr[0], self::getDaysBetweenSolar($dateArr[0], $dateArr[1], $dateArr[2], $yearData[1], $yearData[2]));
        }
        $date = date('Y-m-d', strtotime($return[0].'-'.$return[4].'-'.$return[5]));
        return ['date'=>$date, 'info'=>$return];
    }

    /**
     * 获取当前阳历对应的一个月阴历数据
     * @param string $date
     * @return array
     */
    public static function convertSolarMonthToLunar($date='')
    {
        $date = $date?date('Y-n-j', strtotime($date)):date('Y-n-j');
        $dateArr = explode('-', $date);
        $yearIndex = $dateArr[0] - self::$minYear;
        $yearData = self::$lunarInfo[$yearIndex];
        if($dateArr[0]==self::$minYear&&$dateArr[1]<=2&&$dateArr[2]<=9) return array(1891,'正月','初一','辛卯',1,1,'兔');
        $month_days_ary = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        $dd = $month_days_ary[$dateArr[1]];
        if(self::isLeapYear($dateArr[0]) && $dateArr[1] == 2) $dd++;
        $lunar_ary = [];
        for ($i = 1; $i < $dd; $i++)
        {
            $array = self::getLunarByBetween($dateArr[0],self::getDaysBetweenSolar($dateArr[0], $dateArr[1], $i, $yearData[1], $yearData[2]));
            $array[] = $dateArr[0] . '-' . $dateArr[1] . '-' . $i;
            $lunar_ary[$i] = $array;
        }
        return $lunar_ary;
    }

    /**
     * 将阴历转换为阳历
     * @param year 阴历-年
     * @param month 阴历-月,闰月处理:例如如果当年闰五月,那么第二个五月就传六月,相当于阴历有13个月,只是有的时候第13个月的天数为0
     * @param date 阴历-日
     */
    public static function convertLunarToSolar($date='')
    {
        $date = $date?date('Y-n-j', strtotime($date)):date('Y-n-j');
        $dateArr = explode('-', $date);
        $yearIndex = $dateArr[0] - self::$minYear;
        $yearData = self::$lunarInfo[$yearIndex];

        $between = self::getDaysBetweenLunar($dateArr[0],$dateArr[1],$dateArr[2]);
        $res = mktime(0,0,0,$yearData[1],$yearData[2],$dateArr[0]);
        $res = date('Y-m-d', $res+$between*24*60*60);
        $day = explode('-', $res);
        $year = $day[0];
        $month= $day[1];
        $day = $day[2];
        return $year.'-'.$month.'-'.$day;
    }

    /**
     * 判断是否是闰年
     * @param year
     */
    public static function isLeapYear($year='')
    {
        $year = $year?:date('Y');
        return (($year%4==0 && $year%100 !=0) || ($year%400==0));
    }

    /**
     * 获取干支纪年
     * @param year
     */
    public static function getLunarYearName($year='')
    {
        $year = $year?:date('Y');
        $sky = array('庚','辛','壬','癸','甲','乙','丙','丁','戊','己');
        $earth = array('申','酉','戌','亥','子','丑','寅','卯','辰','巳','午','未');
        $year = $year.'';
        return $sky[$year[3]].$earth[$year%12];
    }

    /**
     * 根据阴历年获取生肖
     * @param year 阴历年
     */
    public static function getYearZodiac($year='')
    {
        $year = $year?:date('Y');
        $zodiac = array('猴','鸡','狗','猪','鼠','牛','虎','兔','龙','蛇','马','羊');
        return $zodiac[$year%12];
    }

    /**
     * 获取阳历月份的天数
     * @param year 阳历-年
     * @param month 阳历-月
     */
    public static function getSolarMonthDays($year='', $month='')
    {
        $year = $year?:date('Y');
        $month = $month?:date('n');
        $monthHash = array('1'=>31,'2'=>self::isLeapYear($year)?29:28,'3'=>31,'4'=>30,'5'=>31,'6'=>30,'7'=>31,'8'=>31,'9'=>30,'10'=>31,'11'=>30,'12'=>31);
        return $monthHash["$month"];
    }

    /**
     * 获取阴历月份的天数
     * @param year 阴历-年
     * @param month 阴历-月,从一月开始
     */
    public static function getLunarMonthDays($year='', $month='')
    {
        $year = $year?:date('Y');
        $month = $month?:date('n');
        $monthData = self::getLunarMonths($year);
        return $monthData[$month-1];
    }

    /**
     * 获取阴历每月的天数的数组
     * @param year
     */
    public static function getLunarMonths($year='')
    {
        $year = $year?:date('Y');
        $yearData = self::$lunarInfo[$year - self::$minYear];
        $leapMonth = $yearData[0];
        $bit = decbin($yearData[3]);
        for ($i = 0; $i < strlen($bit);$i ++) $bitArray[$i] = substr($bit, $i, 1);
        for($k=0,$klen=16-count($bitArray);$k<$klen;$k++) array_unshift($bitArray, '0');
        $bitArray = array_slice($bitArray,0,($leapMonth==0?12:13));
        for($i=0; $i<count($bitArray); $i++) $bitArray[$i] = $bitArray[$i] + 29;
        return $bitArray;
    }

    /**
     * 获取农历每年的天数
     * @param year 农历年份
     */
    public static function getLunarYearDays($year='')
    {
        $year = $year?:date('Y');
        $yearData = self::$lunarInfo[$year-self::$minYear];
        $monthArray = self::getLunarYearMonths($year);
        $len = count($monthArray);
        return ($monthArray[$len-1]==0?$monthArray[$len-2]:$monthArray[$len-1]);
    }

    /**
     * 获取阴历月份对应的总天数
     * @param string $year
     * @return array
     */
    public static function getLunarYearMonths($year='')
    {
        $year = $year?:date('Y');
        $monthData = self::getLunarMonths($year);
        $res = [];
        $yearData = self::$lunarInfo[$year-self::$minYear];
        $len = ($yearData[0]==0?12:13);
        for($i=0;$i<$len;$i++)
        {
            $temp=0;
            for($j=0;$j<=$i;$j++) $temp+=$monthData[$j];
            array_push($res, $temp);
        }
        return $res;
    }

    /**
     * 获取闰月
     * @param year 阴历年份
     */
    public static function getLeapMonth($year='')
    {
        $year = $year?:date('Y');
        $yearData = self::$lunarInfo[$year-self::$minYear];
        return $yearData[0];
    }

    /**
     * 计算阴历日期与正月初一相隔的天数
     * @param date
     */
    public static function getDaysBetweenLunar($date='')
    {
        $date = $date?date('Y-n-j', strtotime($date)):date('Y-n-j');
        $dateArr = explode('-', $date);
        $yearMonth = self::getLunarMonths($dateArr[0]);
        $res=0;
        for($i=1;$i<$dateArr[1];$i++) $res +=$yearMonth[$i-1];
        $res+=$dateArr[2]-1;
        return $res;
    }

    /**
     * 计算2个阳历日期之间的天数
     * @param year 阳历年
     * @param cmonth
     * @param cdate
     * @param dmonth 阴历正月对应的阳历月份
     * @param ddate 阴历初一对应的阳历天数
     */
    public static function getDaysBetweenSolar($year,$cmonth,$cdate,$dmonth,$ddate)
    {
        $a = mktime(0,0,0,$cmonth,$cdate,$year);
        $b = mktime(0,0,0,$dmonth,$ddate,$year);
        return ceil(($a-$b)/24/3600);
    }

    /**
     * 根据距离正月初一的天数计算阴历日期
     * @param year 阳历年
     * @param between 天数
     */
    public static function getLunarByBetween($year='', $between=0)
    {
        $year = $year?:date('Y');
        $lunarArray = [];
        $yearMonth=[];
        $t=0;
        $e=0;
        $leapMonth=0;
        $m='';
        if($between==0)
        {
            array_push($lunarArray, $year,'正月','初一');
            $t = 1;
            $e = 1;
        }
        else
        {
            $year = $between>0? $year : ($year-1);
            $yearMonth = self::getLunarYearMonths($year);
            $leapMonth = self::getLeapMonth($year);
            $between = $between>0?$between : (self::getLunarYearDays($year)+$between);
            for($i=0;$i<13;$i++)
            {
                if($between==$yearMonth[$i])
                {
                    $t=$i+2;
                    $e=1;
                    break;
                }else if($between<$yearMonth[$i])
                {
                    $t=$i+1;
                    $e=$between-(empty($yearMonth[$i-1])?0:$yearMonth[$i-1])+1;
                    break;
                }
            }
            $m = ($leapMonth!=0&&$t==$leapMonth+1)?('闰'.self::getCapitalNum($t- 1,true)):self::getCapitalNum(($leapMonth!=0&&$leapMonth+1<$t?($t-1):$t),true);
            array_push($lunarArray,$year,$m,self::getCapitalNum($e,false));
        }
        array_push($lunarArray,self::getLunarYearName($year));// 天干地支
        array_push($lunarArray,$t,$e);
        array_push($lunarArray,self::getYearZodiac($year));// 12生肖
        array_push($lunarArray,$leapMonth);// 闰几月
        return $lunarArray;
    }

    /**
     * 获取数字的阴历叫法
     * @param num 数字
     * @param isMonth 是否是月份的数字
     */
    public static function getCapitalNum($num,$isMonth=false)
    {
        $dateHash=array('0'=>'','1'=>'一','2'=>'二','3'=>'三','4'=>'四','5'=>'五','6'=>'六','7'=>'七','8'=>'八','9'=>'九','10'=>'十 ');
        $monthHash=array('0'=>'','1'=>'正月','2'=>'二月','3'=>'三月','4'=>'四月','5'=>'五月','6'=>'六月','7'=>'七月','8'=>'八月','9'=>'九月','10'=>'十月','11'=>'冬月','12'=>'腊月');
        $res='';
        if($isMonth) $res = $monthHash[$num];
        else
        {
            if($num<=10) $res = '初'.$dateHash[$num];
            else if($num>10&&$num<20) $res = '十'.$dateHash[$num-10];
            else if($num==20) $res = "二十";
            else if($num>20&&$num<30) $res = "廿".$dateHash[$num-20];
            else if($num==30) $res = "三十";
        }
        return $res;
    }

    /**
     * 节气通用算法
     * @param string $date
     * @return array
     */
    public static function getJieQi($date='')
    {
        $date = $date?date('Y-n-j', strtotime($date)):date('Y-n-j');
        $dateArr = explode('-', $date);
        $year = substr($dateArr[0],-2)+0;
        $coefficient = array(
            array(5.4055,2019,-1),//小寒
            array(20.12,2082,1),//大寒
            array(3.87),//立春
            array(18.74,2026,-1),//雨水
            array(5.63),//惊蛰
            array(20.646,2084,1),//春分
            array(4.81),//清明
            array(20.1),//谷雨
            array(5.52,1911,1),//立夏
            array(21.04,2008,1),//小满
            array(5.678,1902,1),//芒种
            array(21.37,1928,1),//夏至
            array(7.108,2016,1),//小暑
            array(22.83,1922,1),//大暑
            array(7.5,2002,1),//立秋
            array(23.13),//处暑
            array(7.646,1927,1),//白露
            array(23.042,1942,1),//秋分
            array(8.318),//寒露
            array(23.438,2089,1),//霜降
            array(7.438,2089,1),//立冬
            array(22.36,1978,1),//小雪
            array(7.18,1954,1),//大雪
            array(21.94,2021,-1)//冬至
        );
        $term_name = array(
            "小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨",
            "立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑",
            "白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至");
        $idx1 = ($dateArr[1]-1)*2;
        $_leap_value = floor(($year-1)/4);
        $day1 = floor($year*0.2422+$coefficient[$idx1][0])-$_leap_value;
        if(isset($coefficient[$idx1][1])&&$coefficient[$idx1][1]==$dateArr[0]) $day1 += $coefficient[$idx1][2];
        $day2 = floor($year*0.2422+$coefficient[$idx1+1][0])-$_leap_value;
        if(isset($coefficient[$idx1+1][1])&&$coefficient[$idx1+1][1]==$dateArr[0]) $day1 += $coefficient[$idx1+1][2];
        //echo __FILE__.'->'.__LINE__.' $day1='.$day1,',$day2='.$day2.'<br/>'.chr(10);
        $data=[];
        if($dateArr[2]<$day1){
            $data['name1']=$term_name[$idx1-1];
            $data['name2']=$term_name[$idx1-1].'后';
        }else if($dateArr[2]==$day1){
            $data['name1']=$term_name[$idx1];
            $data['name2']=$term_name[$idx1];
        }else if($dateArr[2]>$day1 && $dateArr[2]<$day2){
            $data['name1']=$term_name[$idx1];
            $data['name2']=$term_name[$idx1].'后';
        }else if($dateArr[2]==$day2){
            $data['name1']=$term_name[$idx1+1];
            $data['name2']=$term_name[$idx1+1];
        }else if($dateArr[2]>$day2){
            $data['name1']=$term_name[$idx1+1];
            $data['name2']=$term_name[$idx1+1].'后';
        }
        return $data;
    }

    /**
     * 获取节日:特殊的节日只能修改此函数来计算
     * @param $today
     * @param false $nl_info
     * @param int $config
     * @return string
     */
    public static function getFestival($today='', $nl_info=false, $config = 1)
    {
        $today = $today?date('Y-n-j', strtotime($today)):date('Y-n-j');
        if($config == 1){
            $arr_lunar=array('01-01'=>'春节','01-15'=>'元宵节','02-02'=>'二月二','05-05'=>'端午节','07-07'=>'七夕节','08-15'=>'中秋节','09-09'=>'重阳节','12-08'=>'腊八节','12-23'=>'小年');
            $arr_solar=array('01-01'=>'元旦','02-14'=>'情人节','03-12'=>'植树节','04-01'=>'愚人节','05-01'=>'劳动节','06-01'=>'儿童节','10-01'=>'国庆节','10-31'=>'万圣节','12-24'=>'平安夜','12-25'=>'圣诞节');
        }
        //需要不同节日的,用不同的$config,然后配置$arr_lunar和$arr_solar
        $festivals = [];
        list($y,$m,$d) = explode('-',$today);
        if(!$nl_info) $nl_info = self::convertSolarToLunar($today);
        if($nl_info['info'][7]>0&&$nl_info['info'][7]<$nl_info['info'][4]) $nl_info['info'][4]-=1;
        $md_lunar = substr('0'.$nl_info['info'][4],-2).'-'.substr('0'.$nl_info['info'][5],-2);
        $md_solar=substr_replace($today,'',0,5);
        isset($arr_lunar[$md_lunar])?array_push($festivals, $arr_lunar[$md_lunar]):'';
        isset($arr_solar[$md_solar])?array_push($festivals, $arr_solar[$md_solar]):'';
        $glweek = date("w",strtotime($today));  //0-6
        if($m==5&&($d>7)&&($d<15)&&($glweek==0))array_push($festivals, "母亲节");
        if($m==6&&($d>14)&&($d<22)&&($glweek==0))array_push($festivals,"父亲节");
        $jieqi = self::getJieQi($today);
        $jieqi = isset($jieqi)?$jieqi['name1']:'';
        if($jieqi) array_push($festivals, $jieqi);
        return implode('/',$festivals);
    }

    /**
     * 获取当前时间属于哪个时辰
     * @param $h
     * @return string
     */
    public static function getTheHour($h='')
    {
        $d=$h?$h:date('G');
        if($d==23 || $d==0){
            return '子时';
        }else if($d==1 || $d==2){
            return '丑时';
        }else if($d==3 || $d==4){
            return '寅时';
        }else if($d==5 || $d==6){
            return '卯时';
        }else if($d==7 || $d==8){
            return '辰时';
        }else if($d==9 || $d==10){
            return '巳时';
        }else if($d==11 || $d==12){
            return '午时';
        }else if($d==13 || $d==14){
            return '未时';
        }else if($d==15 || $d==16){
            return '申时';
        }else if($d==17 || $d==18){
            return '酉时';
        }else if($d==19 || $d==20){
            return '戌时';
        }else if($d==21 || $d==22){
            return '亥时';
        }
    }

}