项目中需要将一个文件进行简单的加密,所以就记录一下,话不多说,直接撸代码
操作步骤
-
加密过程
public function test_encode(){ // echo __DIR__.'\server.php'; $filename = './test.sql'; $res = $this->encode_file_contents($filename); echo "OK,加密完成!" ; } // 加密方法 public function encode_file_contents($filename){ $type=strtolower(substr(strrchr($filename,'.'),1)); if ('php' == $type && is_file($filename) && is_writable($filename)) { // 如果是PHP文件 并且可写 则进行压缩编码 $contents = file_get_contents($filename); $contents = php_strip_whitespace($filename); // 去除PHP头部和尾部标识 $headerPos = strpos($contents,'<?php'); $footerPos = strrpos($contents,'?>'); $contents = substr($contents, $headerPos + 7, $footerPos - $headerPos-8); $encode = base64_encode(gzdeflate($contents)); // 开始编码 $encode = '<?php'."\r\treturn(gzinflate(base64_decode("."'".$encode."'".")));\r?>"; return file_put_contents($filename, $encode); }else{// 非php文件的加密操作 $contents = file_get_contents($filename); $encode = base64_encode($contents); // 开始编码 return file_put_contents($filename, $encode); } return false; }
-
解密过程
public function test_decode(){ $filename = './test.sql'; $res = $this->decode_file_contents($filename); echo "OK,解密完成!" ; } //解密过程 public function decode_file_contents($filename){ $type=strtolower(substr(strrchr($filename,'.'),1)); if ('php' == $type && is_file($filename) && is_writable($filename)) { // 如果是PHP文件 并且可写 则进行压缩编码 $contents = file_get_contents($filename); $contents = php_strip_whitespace($filename); // 去除PHP头部和尾部标识 $headerPos = strpos($contents,'<?php'); $footerPos = strrpos($contents,'?>'); $contents = substr($contents, $headerPos + 7, $footerPos - $headerPos-8); $decode = eval($contents); // 开始编码 $decode = "<?php"."\r\t".$decode."\r?>"; return file_put_contents($filename, $decode); }else{ $contents = file_get_contents($filename); $decode = base64_decode($contents); // 开始编码 return file_put_contents($filename, $decode); } return false; }
亲测有效,这里只进行了简单的加密操作,有需要可以进行升级版的加密。
就写到这里了,好长时间没写,有点怠慢了。
结论
应该还有更高级的加密方式,能力有限,只能做到这一块,有新的想法还会继续更新。
如果您对这个文章有任何异议,那么请在文章评论处写上你的评论。
愿大家都能在编程这条路,越走越远。
有些妹子喜欢带上墨镜自拍。其实再戴上口罩,会显得更美。多照照镜子,很多事情你就明白原因了。