Skip to content
Advertisement

PHP encode and decode text to ASCII characters

I plan to make a class that can encode files into ASCII characters and decode into readable texts. Basically, the idea of my encoding is to encode all non-space characters into ASCII and replace the spaces into random non-numeric characters.

Example: "Hello World!" to "72101108108111^8711111410810033" 

In this manner, if I have an entire file with multiple paragraphs and encode it, it wouldn’t be so obvious that I converted the characters to ASCII. So far this is my code:

$text = str_split("Hello World!");
$content = "";
$random = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*-+?/_=");
foreach($text as $t){
    if ($t == " "){
        $count = rand(1,66);
        $content .= $random[$count-1];
    }
    else
        $content .= ord($t);
}
echo $content."<br>";
$decode = str_split($content);
$script = "";
$tostring = "";
foreach($decode as $d){
    if (is_numeric($d)){
        $tostring .= $d;
    }else{
        $script .= chr($tostring);
        $tostring = "";
    }
}

echo $script;

I’m struggling to figure out the problem with my code. This is the result of it:

ASCII: 72101108108111-8711111410810033
TEXT: O

Please enlighten me!

Advertisement

Answer

Two problems: you were attempting to pass multiple numbers to chr() which is designed to return a single character, and you had no way to tell how long your numbers were going to be. Using your example above: is it 72, 101, 108, 108 or is it 72, 10, 10, 81, 08? So, fix your numbers at 3 digits using sprintf() and then you’ll know when to pass data to chr() and continue with your decoding.

$text = str_split("Hello World!");
$content = "";
$random = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*-+?/_=");
foreach($text as $t){
    if ($t === " "){
        $count = rand(1, 66);
        $content .= $random[$count - 1];
    } else {
        // this will always be three digits now
        $content .= sprintf("%03d", ord($t));
    }
}
echo $content."<br>";
$decode = str_split($content);
$script = "";
$tostring = "";
foreach($decode as $d){
    if (is_numeric($d)){
        $tostring .= $d;
        if (strlen($tostring) === 3) {
            // you've got 3 numbers so you can decode and reset
            $script .= chr($tostring);
            $tostring = "";
        }
    } else {
        // also you weren't putting your spaces back in
        $script .= " ";
    }
}

echo $script;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement