私はPHPを初めて使いました。あなたのコードを整理する最良の方法はなんですか?私はPHP(testexec.php)を使ってリモートサーバと話すためにクライアント側でフォーム(form.php)で何かをしようとしています。私は私のtestexec.phpがform.phpファイルから変数にアクセスする必要があるので、form.phpにすべてのコードを入れて変数を呼び出す必要はないのだろうかと疑問に思っています別のPHPファイルから。この状況でコードをどのように整理しますか?だから今、私は何とか動作するように、次のコードのために私のform.phpから 'ゲートウェイ' の値を取得する必要がありますコードを整理するにはPHP
form.php
<div class="box1">
<form method="post">
<label class="col">Up/Dowb</label>
<span class="col">
<input type="radio" name="option" id="r1" value="1" />
<label for="r1">Up</label>
<input type="radio" name="option" id="r2" value="2" />
<label for="r2">Down</label>
</span>
<span class="col">
<input type="submit" class="button"/>
</span>
</form>
</div>
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(".button").click(function(event){
if ((document.getElementsByName("gateway")[0].value == '')) {
alert('Gateway Required!');
return false;
}
else if (document.querySelectorAll('input[type="radio"]:checked').length < 1) {
alert('Please Choose Up/Down Value!');
return false;
}
else {
//alert('Sucess!');
event.preventDefault();
$.ajax({
url:"testexec.php",
type: "POST",
data: {option: $('input[type=radio]:checked').val()},
dataType: "text",
success:function(result){
$('#div1').html(result)
}
});
return true;
}
});
</script>
<div id="div1"></div>
</body>
</html>
testexec.php
$gateway = '';
$user = 'user';
$pwd = 'pass';
function cleanInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$gateway = cleanInput($_POST['gateway']); //need to get the value of gateway from form.php
//create the ssh connection
if ($connection = @ssh2_connect($gateway, 22)) {
ssh2_auth_password($connection, $user, $pwd);
if(isset($_POST['option']) && $_POST['option'] == 1) {
$stream = ssh2_exec($connection, "/tmp/user/testscripts/up.sh");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo '<pre>' . stream_get_contents($stream_out) . '</pre>';
}
if(isset($_POST['option']) && $_POST['option'] == 2) {
$stream = ssh2_exec($connection, "/tmp/user/testscripts/down.sh");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo nl2br(stream_get_contents($stream_out));
}
}
}
?>
:
$gateway = cleanInput($_POST['gateway']);
私はこれがこのようなものを分離するために実用的であるかどうか疑問に思っていましたか?
MVCを参照してください。 MVCはソフトウェアのアーキテクチャパターンです。 MVCの原則を遵守すると、PHPフレームワークの多くが自然にコードを整理しています。調べるべき他のアーキテクチャーパターンがありますが、1つを採用すると、すべてのコードが多かれ少なかれ、どこに行くのかがわかります。 –