php源码升级php7指南

php7中已经不可使用的旧方法及类库

  1. mysql 扩展 已经不再支持
  2. mcrypt 扩展不再支持
  3. 不支持grep 函数了。已经废弃了
  4. 不支持类名同名构造函数

mysql扩展的替换

mysql 系列函数已经废弃掉了。取而代之的是mysqli系列函数.如采用框架可直接无缝切换为mysqli的数据库操作函数

mcrypt 系列函数替换为OpenSsl

以3des 算法 及 des算法为例子

低版本代码

$value = $this->PaddingPKCS7($data);
$key =$this->desKey;
$iv  = $this->desIv;        
$cipher = "DES-EDE3-CBC";
if (in_array($cipher, openssl_get_cipher_methods())) {
    $result = openssl_encrypt($value, $cipher,$key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
}

//printf("%s => %s\n", bin2hex($value), bin2hex($result));exit;
return $result;

SSL

$value = $this->PaddingPKCS7($value);
$message_padded = $value;
$key = $this->desKey;
if (strlen($message_padded) % 8) {
    $message_padded = str_pad($message_padded,strlen($message_padded) + 8 - strlen($message_padded) % 8, "\0");
}

$result = openssl_encrypt($message_padded, "DES-EDE3",$key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
//$result = openssl_encrypt($value, $cipher, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);          
$result = base64_encode($result);

return $result;

Des加密算法低版本

$block = mcrypt_get_block_size('des', 'ecb');

if (($pad = $block - (strlen($prep_code) % $block)) < $block) {
    $prep_code .= str_repeat(chr($pad), $pad);
}

$encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB);
return base64_encode($encrypt);

Des Openssl

$prep_code = serialize($data);
$encrypt = openssl_encrypt ($prep_code, 'des-ecb', $key);
return base64_encode($encrypt);

grep函数替换

grep 函数是老版本的正则表达式匹配函数。有些老系统会出现这个函数

现在grep可以替换为preg_grep

不支持类名构造函数

你的老代码可能类似这样

class{
    class(){

    }
}

现在此是不允许的.
改成这样

class{
    __construct(){

    }
}

最后附上一个完整代码


class CryptOpenssl{
    private $hash;

    function __construct($hash){
        $key = md5($hash,TRUE);
        $key .= substr($key,0,8);
        $this->hash = $key;
    }

    /**
     * @param $data
     * @return string
     */
    public function Encrypt($data){
        $encData = openssl_encrypt($data, 'DES-EDE3', $this->hash, OPENSSL_RAW_DATA);

        $encData = base64_encode($encData);

        return $encData;
    }

    /**
     * @param $data
     * @return string
     */
    public function Decrypt($data){
        $data = base64_decode($data);

        $decData = openssl_decrypt($data, 'DES-EDE3', $this->hash, OPENSSL_RAW_DATA);

        return $decData;
    }
}

function encrypt($data, $key)
{
    $prep_code = serialize($data);
    $encrypt = openssl_encrypt ($prep_code, 'des-ecb', $key,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING);
    return base64_encode($encrypt);
}

function decrypt($str, $key)
{
    $str = base64_decode($str);
    $str = openssl_decrypt ($str, 'des-ecb', $key,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING);
    return unserialize($str);
}

添加新评论