create a caesar cipher function in php

To create a Caesar cipher function in PHP, you can follow these steps:

  1. Define a function named caesarCipher that takes two parameters: the plaintext to be encrypted and the shift value.
  2. Convert the plaintext to uppercase to ensure consistent handling of characters.
  3. Create an empty string to store the ciphertext.
  4. Loop through each character in the plaintext.
  5. If the character is a letter (A-Z), shift it by the specified value, wrapping around to the beginning of the alphabet if necessary.
  6. Append the shifted character to the ciphertext string.
  7. If the character is not a letter, append it to the ciphertext string without modification.
  8. Finally, return the ciphertext string.

Here's the PHP code for the Caesar cipher function:

main.php
function caesarCipher($plaintext, $shift) {
    $ciphertext = "";

    $plaintext = strtoupper($plaintext);

    for ($i = 0; $i < strlen($plaintext); $i++) {
        $char = $plaintext[$i];

        if (ctype_alpha($char)) {
            $ascii = ord($char);
            $ascii = ($ascii + $shift - 65) % 26 + 65;
            $char = chr($ascii);
        }

        $ciphertext .= $char;
    }

    return $ciphertext;
}
421 chars
20 lines

You can use this function by calling it and passing the plaintext and the desired shift value. Here's an example usage:

main.php
$plaintext = "Hello, World!";
$shift = 3;

$ciphertext = caesarCipher($plaintext, $shift);

echo $ciphertext; // Outputs: KHOOR, ZRUOG!
136 chars
7 lines

Make sure to choose a shift value that works well for your purposes.

gistlibby LogSnag