나는 PHP로 AJAX를 통해 명령을 게시하는 간단한 JS 터미널 쉘 에뮬레이터를 구축하고 있습니다.
보안을 제쳐두고 두십시오. 이는 학습 및 데모 목적으로 만 사용하십시오. 이제 문제는 str_replace()가 예상대로 작동하지 않는다는 것입니다. 실제로는 변경되지 않은 입력 문자열을 반환합니다. 그것은 다음과 같이 작동합니다 :
이 The name of this host is $hostname
->Yes, this string contains a variable
->Replace $hostname with testserver
-> 내가 잘못 뭐하는 거지 The name of this host is testserver
PHP - str_replace가 원래 문자열을 반환
을 반환?
이 echo
및 export
에 대한 나의 응답 스크립트입니다 :
<?
// get environment variables from JSON
$vars = json_decode(file_get_contents('environment.json'), true);
// get request params
$method = $_SERVER['REQUEST_METHOD'];
$action = $_POST['action'];
$data = $_POST['data'];
switch ($action) {
case 'echo':
$cmd = $data;
// if the string in question contains a variable, eg. "the time is $time"
if (strpos($cmd,'$')) {
$output = '';
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var,$val,$cmd);
}
echo $output;
} else {
// if it does not contain a variable, answer back the query string
// ("echo " gets stripped off in JS)
echo $cmd;
}
break;
case 'export':
// separate a variable declaration by delimiter "="
$cmd = explode('=',$data);
// add a $-sign to the first word which will be our new variable
$var = '$' . array_shift($cmd);
// grab our variable value from the array
$val = array_shift($cmd);
// now append everything to the $vars-array and save it to the JSON-file
$vars[$var] = $val;
file_put_contents("environment.json",json_encode($vars));
break;
}
이 environment.json –
의 내용을 표시하십시오 이유는 않는 str_replace의 사용에서 찾을 수없는, 그래서 조합'$ var','$의 val'과'게시하시기 바랍니다 $ cmd'를 사용합니다. – Alexander
'strpos ('strpos ($ cmd, '$'))!를 사용해야하므로'strpos'를주의 깊게 읽으십시오. 처음에 찾으려는 단어가'0'이 아니라'false'가 아닙니다. == false' – Sal00m