2013-08-03 48 views
3

有了很多幫助,我創建了一個腳本來編輯我的VPS上的文件。它一直在努力工作,但我有一個問題讓我完全陷入困境。當我需要將文件中的值調整爲0時,它不起作用。除0(value="0")外,幾乎任何其他值都可以使用(即value="3")。我很困惑。我需要腳本更改顏色值= color=0我不知道爲什麼0不會工作,但任何其他數字或字母會。這裏是我的代碼:PHP表單不會提交value =「0」

<?php 
//Color 
    $color = explode("=", trim($contents[1])); 

    if(isset($_REQUEST['difficulty_choice'])){ 
     exec('sed -i '.escapeshellarg('s/color=.*/color='.$_REQUEST['color_choice'].'/g')." /home/user/color.props"); 
     echo 'Color choice has been updated'; 
    } 

?> 


<?php echo $contents[1]; //Color ?> 
<form method="get" action="update.php"> 
    <select name="color_choice">; 
     <option value="0" <?php if($color[1] == '0'){?>selected="selected"<?php }?>>Red</option>; 
     <option value="1" <?php if($color[1] == '1'){?>selected="selected"<?php }?>>Blue</option>; 
     <option value="2" <?php if($color[1] == '2'){?>selected="selected"<?php }?>>Black</option>; 
     <option value="3" <?php if($color[1] == '3'){?>selected="selected"<?php }?>>Yellow</option>; 
    </select> 
    <input type="submit" name="Submit" value="Submit" /> 
</form> 

文件內容:

# The color file 
color=1 

更新:我換空與isset和它的作品!

回答

4

在php中,當$val = "0",empty($val)評估爲true。這是意想不到的,但這是php的方式。 php docs for empty() give you a list of values considered empty under the "Return Values" section。這裏有一個小的測試腳本來證明這一點:

<?php 
$val = "0"; 
if (empty($val)) { 
     echo $val . " is empty!\n"; 
} else { 
     echo $val . " is not empty.\n"; 
} 

$val = "1"; 
if (empty($val)) { 
     echo $val . " is empty!\n"; 
} else { 
     echo $val . " is not empty.\n"; 
} 
?> 

輸出是:

0 is empty! 
1 is not empty. 

===操盤empty()考慮使用其它類型的檢查。

+2

isset應該在這裏而不是空的 – Orangepill

+0

isset做的伎倆,謝謝! – jcrane

0

如果你想檢查整數,比較整數時不應該使用引號。改爲像這樣做。

<?php 
$cmpColor = intval($color[1]); //Make sure to compare with an integer. This way you can use === to compare (because $cmpColor and 0,1,2 or 3 are of the same type as well) 
?> 

<select name="color_choice">; 
    <option value="0" <?php if($cmpColor === 0){?>selected="selected"<?php }?>>Red</option>; 
    <option value="1" <?php if($cmpColor === 1){?>selected="selected"<?php }?>>Blue</option>; 
    <option value="2" <?php if($cmpColor === 2){?>selected="selected"<?php }?>>Black</option>; 
    <option value="3" <?php if($cmpColor === 3){?>selected="selected"<?php }?>>Yellow</option>; 
</select>