I have written a possible solution for your problem - see code below. You can find a working copy of this at http://www.floris.us/SO/codeForm.php
The key to solving your specific problem is right near the bottom; I use
<script type="text/javascript">
document.forms['codeForm'].codeMsg.value = <?php echo '"'.$newString.'"'; ?>;
document.forms['codeForm'].msg.value = <?php echo '"'.$string.'"'; ?>;
</script>
to take the value of a php variable and put it in an input area of the form.
<html>
<form class="form-inline" name="codeForm" role="form" method="post">
<div class="table-responsive">
<table>
<tr class="tr_top">
<!-- <th class="th_left_top">Message:</th> -->
<td class="td_top">
Plain text message<br>
<textarea class="form-control" rows="3" name="msg"
<?php
if (isset($_POST['encode'])) {
echo 'value = "'.htmlspecialchars($_POST['msg']).'"';
}
else {
echo 'placeholder = "Your message here"';
}
?>
onfocus='this.select()'>
</textarea>
</td>
<td class="td_top">
Coded message<br>
<textarea class="form-control" rows="3" name="codeMsg"
<?php
if (isset($_POST['decode'])) {
echo "value=".htmlspecialchars($_POST['codeMsg']);
}
else {
echo 'placeholder = "Encoded message here. "';
}
?>
onfocus='this.select()'>
</textarea>
</td>
</tr>
<tr class="tr_mid">
<td class="td_mid">
<input type=text class="form-control input_mid" name="offset"
<?php
if (isset($_POST['encode'])) {
echo 'value = "'.htmlspecialchars($_POST['offset']).'"';
}
else {
echo 'placeholder = "Enter a number:"';
}
?>
>
</td>
</tr>
<tr class="tr_bottom">
<!-- <th class="th_bottom empty"></th> -->
<td class="td_bottom">
<input class="input_bottom btn btn-default" type="submit" name="encode" value="Encode">
<input class="input_bottom btn btn-default" type="submit" name="decode" value="Decode">
<input class="input_bottom btn btn-default" type=button value='Clear' onclick='this.form.elements.msg.value=""' </td>
</tr>
</table>
</div>
<!-- close table-responsive -->
</form>
<?php
$string = defaultKey($_POST, 'msg', '');
$offset = defaultKey($_POST, 'offset', 0);
$newString = defaultKey($_POST, 'codeMsg', '');
if(isset($_POST['encode'])) {
$newString = caesar($string, $offset);
}
if(isset($_POST['decode'])) {
$string = caesar($newString, -$offset);
}
function caesar($input, $offset) {
$output = array();
foreach(str_split($input) as $k=>$i) {
if (ctype_alpha($i)) {
$oldChar = strtoupper($i);
$newChar = chr(((ord($oldChar) - ord('A')) + $offset) % 26 + ord('A'));
if($i!=strtoupper($i)) { $newChar = strtolower($newChar); }
}
else {
$newChar = $i;
} // don't do anything with punctuation
$output[$k]=$newChar;
}
$output = implode($output);
return $output;
}
function defaultKey($arr, $key, $default) {
if(isset($arr[$key])) {
return $arr[$key];
}
return $default;
}
?>
<script type="text/javascript">
document.forms['codeForm'].codeMsg.value = <?php echo '"'.$newString.'"'; ?>;
document.forms['codeForm'].msg.value = <?php echo '"'.$string.'"'; ?>;
</script>
</html>