php中包含if条件的文件


file include with if condition in php?

我的html就像这个

<form name="time" method="POST" action="add.php">
    <input type="text" name="empcode" id="empcode" class="textbox" placeholder="822"/><br />
    <input type="text" name="totaltime" id="totaltime" class="textbox" value = "50" /><br />
    <strong>Start Date</strong><input type="date" name="sday"><br />
    <strong>End Date</strong><input type="date" name="eday"><br />
    <input type="submit" class="submit-button" value="Submit"/>
</form>

当用户在$_POST['sday']$_POST['sday']中填充数据时,add.php文件将包括file.php,否则为file2.php

我在add.php 中尝试过

if(isset($_POST['sday']) && isset($_POST['eday'])){
    include('file1.php');
}
else{
    include('file2.php');
}

但它不起作用,我应该用零值检查吗?

使用!empty()而不是isset()。这些字段将始终被设置,至少设置为一个空字符串。

if ( !empty($_POST['sday']) && !empty($_POST['eday']) ) {

isset()仅检查变量是否已定义且不等于null。如果未填写已过帐的值,则该值很可能是一个空字符串。

因此,您也应该检查空字符串:

if (isset($_POST['sday'], $_POST['eday']) && 
        strlen($_POST['sday']) && 
        strlen($_POST['eday'])) {

为什么不empty()

您也可以使用empty(),但由于empty('0')会产生true,您将需要一个额外的条件,从而导致更麻烦的代码。