· 7 years ago · Jul 23, 2018, 07:24 PM
1<?php
2/*
3* Caesar Decryption In PHP
4* Ceded by Himel
5* On 15th July 2018
6* GitHub Username: Swe-HimelRana
7*/
8
9 function caesarEncrypt($text, $key){
10 // Checking text if it has space I want to create cipher all world indivusally so that when user will decode it he will get original paragraph with spacing.
11 $word = explode(" ", $text);
12 $word = array_map('trim', $word); // I like to remove any space in every word just extra code you can avoid it. (This is my habit :P)
13 // So that we got our word let's get our key.
14
15 // Key should be numaric Needed a validation
16 $encryptionKey = $key;
17 if(!filter_var($key, FILTER_VALIDATE_INT)){
18 $error = "Key must be Integer";
19 return $error;
20 die();
21 }
22
23 // Let's check key is negative or positive
24 if($key < 0){
25 $error = "Please Provide a positive key";
26 return $error;
27 die();
28 }
29 // Let's chek our text only contain alphabets and space
30 if(ctype_alpha(str_replace(' ', '', $text)) === false){
31 $error = "Only English Alphabets and Space Please!";
32 return $error;
33 die();
34 }
35 // Let's convert words to uppercase
36 $word = array_map('strtoupper', $word);
37
38 // Now let's create number of all alphabet
39 $alphabet = range('A', 'Z');
40
41 // Now encryption time ..
42 $decryptedText =array(); // array for storing decrypted alphabets
43
44 for ($i=0; $i < count($word) ; $i++) {
45
46 for ($j=0; $j < strlen($word[$i]) ; $j++) {
47 // Getting alphabet code
48 $code = array_search($word[$i][$j], $alphabet);
49
50 $code = $code - $encryptionKey;
51 // Getting negative number and working with We don't allow any nagative code ! :P
52 while($code < 0){
53 $code = 26 + $code;
54 }
55 // Getting code to alphabet
56 // Before converting let's check if it upper then 25
57 while($code > 25){
58 // If code upper then 25 get result of code % 26 as code
59 $code = intval($code % 26);
60
61 }
62
63 // Now convert Cipher text and add to array
64 array_push($decryptedText, $alphabet[$code]);
65 }
66 // Adding Space between every word
67 array_push($decryptedText, ' ');
68 }
69
70 $decrypted = implode("", $decryptedText);
71 return $decrypted;
72 }
73
74 // Now take input from url as url encoded
75 $plainText = urldecode($_GET['text']);
76 $secretKey = urldecode($_GET['key']);
77 // Finally Print result
78 echo caesarEncrypt($plainText, $secretKey);
79?>