在PHP中,fgetc()
函數(shù)用于從文件中讀取一個(gè)字符。結(jié)合其他文件操作函數(shù)和加密/解密算法,你可以實(shí)現(xiàn)文件的加密和解密。以下是一個(gè)使用fgetc()
的簡(jiǎn)單加密和解密示例:
fgetc()
逐字符讀取文件內(nèi)容,并使用ord()
函數(shù)獲取每個(gè)字符的ASCII值。然后,使用自定義的加密算法(例如,簡(jiǎn)單的凱撒密碼)對(duì)每個(gè)字符進(jìn)行加密。function encrypt($input, $key) {
$output = '';
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
$char = $input[$i];
$ascii = ord($char);
$shifted = $ascii + $key;
$output .= chr($shifted % 128); // 限制在ASCII范圍內(nèi)
}
return $output;
}
fgetc()
逐字符讀取加密文件內(nèi)容,并使用ord()
函數(shù)獲取每個(gè)字符的ASCII值。然后,使用相同的加密算法(在這個(gè)例子中是凱撒密碼)對(duì)每個(gè)字符進(jìn)行解密。function decrypt($input, $key) {
$output = '';
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
$char = $input[$i];
$ascii = ord($char);
$shifted = $ascii - $key;
$output .= chr($shifted % 128); // 限制在ASCII范圍內(nèi)
}
return $output;
}
$inputFile = 'original.txt';
$outputFile = 'encrypted.txt';
$key = 3; // 凱撒密碼中的位移量
$file = fopen($inputFile, 'r');
$encryptedFile = fopen($outputFile, 'w');
while (($char = fgetc($file)) !== false) {
$encryptedChar = encrypt($char, $key);
fwrite($encryptedFile, $encryptedChar);
}
fclose($file);
fclose($encryptedFile);
$inputFile = 'encrypted.txt';
$outputFile = 'original.txt';
$file = fopen($inputFile, 'r');
$decryptedFile = fopen($outputFile, 'w');
while (($char = fgetc($file)) !== false) {
$decryptedChar = decrypt($char, $key);
fwrite($decryptedFile, $decryptedChar);
}
fclose($file);
fclose($decryptedFile);
請(qǐng)注意,這個(gè)示例使用了簡(jiǎn)單的凱撒密碼加密算法,它不是安全的加密方法。在實(shí)際應(yīng)用中,你應(yīng)該使用更強(qiáng)大和安全的加密算法,如AES或RSA。