只有当javascript语句为真时,才执行php代码
我尝试执行php代码,具体取决于确认复选框的值如何,就像在此代码段中一样。只有当javascript语句为真时,才执行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命令?这甚至有可能吗?
PHP是一种服务器端语言,所以你可以从不是执行它从你的客户端JavaScript。期。对话框没有显示,因为你有一些JS错误,执行该命令是因为HTML在服务器上呈现,并且在将整个HTML发送到浏览器之前执行PHP。
顺便说一句,你不应该做一个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请求(S)的部分:
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 ;)
为什么我不应该在确认对话框上执行'shell_exec'?你能告诉我代码有什么问题吗?我找不到错误。 – Black
那么,首先它不会工作,你需要确认对话框后的AJAX。你可以这样做,但你必须确保唯一可以调用它的用户拥有正确的权限,服务器必须被保存为地狱,因为在shel_exec允许的情况下,你可能会遇到真正的大问题。如果它只是在你自己的网络上运行,并且没有任何外部任何人的访问,那么确定没有问题,否则你应该谷歌类似shell_exec的安全性,即使你正在做所有的事情来保存它,例如问题可能是一些上传目录,在那里可以创建一个shellscrip .. – swidmann
Thx这些有用的信息!我只在本地主机上运行它,所以没问题。每一个命令都必须得到我的允许。 – Black
您可以尝试AJAX
发送到PHP用于执行了shell_exec一部分,重定向的部分要求能的jQuery内进行管理,你不需要PHP为。但再次shell_exec是非常非常敏感,使用它与预防措施。
代替header("Location: index.php");
代替<?php shell_exec('sudo shutdown -r now'); ?>
使用$.ajax({ code here });
正确答案。 -1没有提到这需要jQuery。由于OP不理解服务器/客户端之间的差异,他可能不会理解这一点。 – Christian
我试过'$ .ajax({sudo shutdown -r now});'没有工作。 – Black
嗨爱德华 '$阿贾克斯({须藤执行shutdown -r now});'这是错误的正确的方法是 '$阿贾克斯({ 网址: “sample.php”, 成功:函数(响应){ console.log(response); }); });' – akashBhardwaj
使用
window.location
,这将是不可能的相反。当JS执行时,PHP已经完成了它的工作。看看“服务器端”与“客户端”语言 –
“php”是作为用户对服务器的网页请求执行的,因此它是**预处理的超文本**无论你在这里尝试过什么都是不可能的。 – Rayon
你可以做的最好的事情是做一个Ajax调用,并执行PHP代码,如果你的JavaScript变量为true .. – Naruto