[英]Execute php code only if javascript statement is true
我嘗試執行php代碼,具體取決於此代碼段中確認復選框的值。
<script>
var check = confirm ('Are you sure ?');
if (check == true)
{
<?php shell_exec('sudo shutdown -r now'); ?>
} else {
<?php
header("Location: index.php");
exit();
?>
}
</script>
但是沒有顯示確認對話框,並且執行了shutdown命令嗎? 這有可能嗎?
Javascript在發送給他后由瀏覽器執行。 在分析答案之前,PHP由服務器執行。 使用XMLHttpRequest來告訴您何時檢查為真。
您可以嘗試AJAX
將請求發送到php以執行shell_exec部分,因為可以在jquery中管理重定向部分,而您不需要php。 但是再次shell_exec 非常非常 敏感 ,請謹慎使用。
代替header("Location: index.php");
使用window.location
代替<?php shell_exec('sudo shutdown -r now'); ?>
<?php shell_exec('sudo shutdown -r now'); ?>
使用$.ajax({ code here });
PHP是一個服務器端語言,所以你不能從你的客戶端的JavaScript執行它。 期。 該對話框未顯示,因為您有一些JS錯誤,由於HTML在服務器上呈現,因此執行了命令,並在將整個HTML發送到瀏覽器之前執行了PHP。
AND,順便說一句,您永遠不要基於這樣的確認對話框來執行shell_exec
。
這可能是一種方法:
HTML的一部分:
<script>
function shutDown() {
if ( confirm ('Are you sure ?') )
{
var xhReq = new XMLHttpRequest();
xhReq.open( "POST", "ajax.php", false );
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.send("cmd=shutdown");
var serverResponse = xhReq.responseText;
alert(serverResponse); // Shows the return from the PHP script
} else {
window.location.href = "index.php";
}
}
</script>
<a href="javascript:void(0)" onclick="javascript:shutDown()"/>shutdown</a>
您的PHP文件(ajax.php)的一部分,用於處理AJAX請求:
if( isset( $_POST["cmd"] ) && $_POST["cmd"] == "shutdown" ) {
// your shutdown code
// I'm not sure if "sudo" really works in this context, because you have to verify with a password, except your php process is already running with sudo rights
shell_exec('sudo shutdown -r now');
}
// you can return something here,
// but it only makes sense if you don't shutdown the server
// you are running the website to shutdown ;)
只要頁面另存為* .php,它就應該起作用
<script>
if (confirm ('Are you sure ?'))
{
<?php shell_exec('sudo shutdown -r now'); ?>
} else {
<?php
header("Location: index.php");
exit();
?>
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.