为什么我的嵌套if/else语句在我的PHP/html脚本中不起作用


Why is my nested if/else statement not working in my PHP/html script?

我正在尝试制作一个可以通过html表单访问的快速PHP脚本。这个想法是让用户输入一个url,PHP脚本应该ping url,并返回成功或失败。我在linux mint机器上有Apache,并且正在通过//localhost进行测试。在PHP中,我使用的是PEAR的Net_Ping包。

当我将url硬编码为ping时,脚本在命令行上运行良好,但当我将其写入html表单时,if-else语句失败。

当我为脚本输入一个url进行ping时,它会回显"ping成功"如果我禁用我的互联网来测试else语句,它仍然会回显"ping成功"

<!DOCTYPE html>
<?php
    require("Net/Ping.php");
    $ping = Net_Ping::factory();
    if ($_POST["url"]) {
        $result = $ping->ping($_POST["url"]);
        if ($result) {
            echo "ping was successful'n";
        } else {
            echo "ping was unsuccessful'n";
        } 
    }
?>
<html>
<body>
<p>This is a free web based URL ping service</p>
<p>Input your favorite URL and see if China is blocking it today!</P>
<form action="<?php test33.php ?>" method="POST">
URL: <input type="text" name="url" /> 
<input type="submit" />
</form>
</body>
</html>

问题就在这里:

<form action="<?php test33.php ?>" method="POST">

应该是:

<form action="test33.php" method="POST">

或:

<form action="<?php echo "test33.php"; ?>" method="POST">

或:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

因此您不必对脚本名称进行硬编码。您也可以将其留空,因为它默认为当前URL:

<form action="" method="POST">

试试这个:

<!DOCTYPE html>
<?php
    require("Net/Ping.php");
    $ping = Net_Ping::factory();
    if ($_POST["url"]) {
        $result = $ping->ping($_POST["url"]);
        if ($result) {
            echo "ping was successful'n";
        } else {
            echo "ping was unsuccessful'n";
        } 
    }
?>
<html>
<body>
<p>This is a free web based URL ping service</p>
<p>Input your favorite URL and see if China is blocking it today!</P>
<form action="" method="POST">
URL: <input type="text" name="url" /> 
<input type="submit" />
</form>
</body>
</html>

您的表单action="有问题。它在另一页中提交。

如果你想在Form中使用<?php tag,你必须这样使用它;

  • 使用echo
  • 使用quete中的文件名。否则php将假定为contant

你的form action就像这里的action="<?php test33.php ?>"; test33.php没有quete

使用周围的quete。就像这个

<form action="<?php echo "test33.php" ?>" method="POST">

已编辑部分。根据文档,如果url为空,ping将返回error array,这意味着你的$result永远不会为假。所以您的代码永远不会运行else语句。要解决此问题在if语句中使用!empty

像这个

if (!empty($_POST["url"])) {
        $result = $ping->ping($_POST["url"]);
        if ($result) {
            echo "ping was successful'n";
        } else {
            echo "ping was unsuccessful'n";
        } 
    }

我认为是因为您的$_POST['url']尚未初始化。你必须在你的if声明中检查它是否存在

if (isset($_POST["url"] && $_POST["url"])