我是新來的PHP,我想知道如何組織您的代碼的最佳方式。我一直試圖在客戶端使用form(form.php)做一些事情,使用PHP(testexec.php)與遠程服務器交談。我已經回到了我的testexec.php需要從form.php文件訪問變量的問題,所以現在我想知道如果我應該把所有的代碼放在form.php中,所以我不必調用變量從一個不同的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));
}
}
}
?>
所以現在我必須從我的form.php的某種方式得到 '門戶' 的價值,爲下面的代碼工作:
$gateway = cleanInput($_POST['gateway']);
所以我想知道這是不是很好,這樣分開的東西?
查找MVC。 MVC是一種軟件架構模式。當您堅持使用MVC原則時,許多PHP框架都會自然地組織您的代碼。還有其他架構模式需要關注,但是當您採用其中一種架構模式時,您會看到所有代碼或多或少地走向應該走的地方。 –