2012-09-19 40 views
2

我的問題是我一個數組值設置爲服務器如下的名稱:PHP從不爲file_exists測試真正在評估數組值

$appserver[$i]=`grep $ip[2] /etc/hosts |awk '{print $2}'`; 

後來我做一個測試,看看服務器上或不(使用wget)。 如果測試失敗我跟蹤該服務器通過與 名稱中使用觸摸創建文件是下來的:

$touch=`touch /home/steve/data/$appserver[$i]; 

文件被創建成功。 稍後,當我去測試文件是否存在時,它永遠不會計算爲true。

if(file_exists('/home/steve/data/$appserver[$i])) { 

我已經嘗試了幾種不同的東西,包括對 $應用程序服務器[$ i]和測試反對它,它也不起作用創建一個新的變量:

我在RHEL上運行PHP 5.1.6 5.

下面是完整的代碼:

$appserver[$i]=`grep $ip[2] /etc/hosts |awk '{print $2}'`; 
    echo "appserver[i] = $appserver[$i]\n"; 
    $get=`wget $key->url 2> /dev/null`; 
    if(file_exists('/home/user/Start')) { 
      $color[$i]="green"; 
      $rm=`rm -rf /home/user/Start`; 
    } 
    else { 
      $color[$i]="red"; 
      if($hostname=="xxxxx") { 
        **if(file_exists('/home/user/data/$appserver[$i]))** {** 
         echo "do nothing appserver file exists\n"; 
         $touch=`touch /home/steve/data/notmailed`; 
         } 
        else { 
        echo "No app file mailed alert\n"; 
        $touch=`touch /home/user/data/$appserver[$i]`; 
        } 
      } 
    } 

謝謝。

+3

''$應用程序服務器[$ i] = 「$應用程序服務器[$ i]」' – raina77ow

回答

1

它應該是:

if(file_exists("/home/steve/data/$appserver[$i]")) { 
+0

謝謝。我試過了一個非常小的程序,顯示了這仍然是失敗的。 [root @ dsmpp1 steve]#ls -l data total 4 -rw-r - r-- 1 root root 0 Sep 19 11:41 test_file [root @ dsmpp1 steve]#cat test_file.php #!/ usr/bin/php -q <?php $ i = 1; $ testarray = array(); $ testarray [$ i] =「test_file」; echo「testarray $ testarray [$ i] \ n」; if(file_exists(「/ home/steve/data/testarray [$ i]」)){ echo「file exists \ n」; } else { echo「文件不存在\ n」; } [根@ dsmpp1史蒂夫]#PHP -q test_file.php testarray test_file裏面 文件不存在 [根@ dsmpp1史蒂夫]# – user1683269

+0

你在你上面粘貼代碼中的錯誤,你如果(file_exists( 「/ home/steve/data/testarray [$ i]」)),正確的是if(file_exists(「/ home/steve/data/$ testarray [$ i]」)) – Nelson

0

試試這個:

$appserver[$i] = "grep $ip[2] /etc/hosts |awk '{print $2}'"; 

//... 

if(file_exists("/home/steve/data/$appserver[$i]")) 
{ 
    //... 
} 

確保您使用雙qoutes(")等。無論您想要的解析爲聲明的字符串變量的內容!

+0

謝謝,但其他人也建議它仍然不起作用。我也用單引號'/home/steve/data'.$appserver[$i]嘗試過,並且不起作用。 – user1683269

+0

請參閱我的更新回答 – Spontifixus

1
if(file_exists('/home/steve/data/$appserver[$i]')) { 

'引用的字符串不插變量值,那麼你正在尋找它的字面名稱爲$appserver[$i]文件。使用"引號代替:

if(file_exists("/home/steve/data/$appserver[$i]")) { 
+0

謝謝,但有人建議,之前,它仍然無法正常工作。 – user1683269

+0

謝謝Marc。我試過使用雙引號,它仍然沒有通過。我硬編碼服務器的名稱以代替$ appserver [$ i],只是爲了確保它在硬編碼時通過。 – user1683269

+0

謝謝。我試過了一個非常小的程序,顯示了這仍然是失敗的。 [root @ dsmpp1 steve]#ls -l data total 4 -rw -r - r-- 1 root root 0 Sep 19 11:41 test_file [root @ dsmpp1 steve]#cat test_file.php #!/ usr/bin/php -q <?php $ i = 1; $ testarray = array(); $ testarray [$ i] =「test_file」; echo「testarray $ testarray [$ i] \ n」; if(file_exists(「/ home/steve/data/testarray [$ i]」)){ echo「file exists \ n」; } 其他{echo「文件不存在\ n」;} } [root @ dsmpp1 steve]#php -q test_file.php testarray test_file 文件不存在 [root @ dsmpp1 steve]# – user1683269