凯撒密码PHP


Caesar Cipher PHP

我从我的代码中得到 2 个错误。或 1 个错误和 1 个通知。

这是通知和问题

注意:未定义的偏移量:0 在 F:''Xampp''htdocs''Encryption''result.php 在第 19 行

警告:in_array() 期望参数 2 是数组,字符串在第 19 行的 F:''Xampp''htdocs''Encryption''result.php 中给出

这是我的代码

索引.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="encrypt" style="position:absolute; left:20%; top:25%;">
    <form method="post" action="result.php">
    <textarea rows="4" cols="50" name="toEncrypt">Enter message to encrypt</textarea>
    <br/>
    <input type="submit" name="encrypt" value="Encrypt">
    </form>
    </div>
    <div id="decrypt" style="position:absolute; right:20%; top:25%;">
    <form method="post" action="result.php">
    <textarea rows="4" cols="50" name="toDecrypt">Enter message to decrypt</textarea>
    <br/>
    <input type="submit" name="decrypt" value="Decrypt">
    </form>
    </div>
</body>

这是我的PHP文件。

<?php
$toEncrypt = $_POST['toEncrypt'];
//$toDecrypt = $_POST['toDecrypt'];
$key = array(
"A" => "B", "B" => "C","C" => "D", "D" => "E","E" => "F","F" => "G",
"G" => "H", "H" => "I", "I" => "J", "J" => "K","K" => "L",
"L" => "M","M" => "N", "N" => "O", "O" => "P", 
"P" => "Q","Q" => "R", "R" => "S","S" => "T","T" => "U", 
"U" => "V", "V" => "W", "W" => "X", "X" => "Y",
"Y" => "Z", "Z" => "Å", "Å" => "Ä", "Ä" => "Ö", "Ö" => "A"
);
//$text2 = $toDecrypt;
$length=strlen($toEncrypt);
$newstr='';
for ($i = 0; $i < $length; $i++) 
{
if (is_array($key) && in_array($toEncrypt[$i], $key[$i]))
{
$newstr=$key[$i];
}
}
echo $newstr;

我无法弄清楚出了什么问题,我认为这对我来说太明显了,太发现它了,提前谢谢。

您必须更改 2 行:

if (is_array($key) && in_array($toEncrypt[$i], $key[$i]))
//...
$newstr=$key[$i];

对此:

if (is_array($key) && in_array(strtoupper($toEncrypt[$i]), array_flip($key)))
                             //^^^^^^^^^^                  ^^^^^^^^^^ To search trough the keys and not the values
                             //|Because your array is in upper case
//...
$newstr .= $key[strtoupper($toEncrypt[$i])];
      //^^      ^^^^^^^^^^So you get the right key
      //|So you append the string