項目中需要將一個文件進行簡單的加密,所以就記錄一下,話不多說,直接擼代碼
操作步驟
-
加密過程
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; }
親測有效,這裏只進行了簡單的加密操作,有需要可以進行升級版的加密。
就寫到這裏了,好長時間沒寫,有點怠慢了。
結論
應該還有更高級的加密方式,能力有限,只能做到這一塊,有新的想法還會繼續更新。
如果您對這個文章有任何異議,那麼請在文章評論處寫上你的評論。
願大家都能在編程這條路,越走越遠。
有些妹子喜歡帶上墨鏡自拍。其實再戴上口罩,會顯得更美。多照照鏡子,很多事情你就明白原因了。