2011-12-24 89 views
0

我似乎無法得到下面的代碼工作?文件是否存在?顯示圖像其他顯示默認圖像

$playerfileLocation = "../wp-content/gallery/playerphotos/' . $playerid . '.jpg"; 
if(file_exits($playerfileLocation)) 
echo "The file File exists"; 
else 
echo "The file File does not exist"; 

「playerid」字段是一個經過的數字。

我似乎無法得到它的工作。 Urgh!

+0

這是相對路徑的工作? – 2011-12-24 04:12:58

+0

否...頁面一旦到達if語句就停止。我在這個「測試」下方顯示的文本沒有被顯示。 – DoubleA 2011-12-24 04:21:41

回答

5

你有不匹配的引號。試試這個代碼。

$playerfileLocation = "../wp-content/gallery/playerphotos/" . $playerid . ".jpg"; 
if(file_exists($playerfileLocation)) 
echo "The file File exists"; 
else 
echo "The file File does not exist"; 

更新: 其實我會建議使用下面的代碼作爲PHP時看到雙引號,它試圖分析在它之間的任何東西,這不是在這種情況下需要。這是性能上的一個小優化。

$playerfileLocation = '../wp-content/gallery/playerphotos/' . $playerid . '.jpg'; 
if(file_exists($playerfileLocation)) 
echo "The file File exists"; 
else 
echo "The file File does not exist"; 

而且,只是檢查文件是否存在,如果不顯示默認圖像使用下面的代碼:

$playerfileLocation = '../wp-content/gallery/playerphotos/' . $playerid . '.jpg'; 
$defaultfileLocation = '../wp-content/gallery/playerphotos/default.jpg'; 
if (!file_exists($playerfileLocation)) { 
    $playerfileLocation = $defaultfileLocation; 
} 
+0

每當PHP看到雙引號時,雙引號的問題有什麼問題,它會嘗試解析它之間的任何內容,在這種情況下這不是必需的。這是一個小的性能優化。** – 2011-12-24 07:14:17

+0

當PHP看到雙引號時,它會嘗試解析它,這需要一些時間(雖然它很少,但仍需要一些時間)。如果你使用單引號,那麼PHP不需要解析它,節省解析它所需的時間。在這種情況下,字符串中沒有任何變量,因此不需要解析它,除非您執行'$ playerfileLocation =「../ wp-content/gallery/playerphotos/$ playerid.jpg」;'這需要PHP解析整個字符串。此外,代碼現在不太可讀。 – Virendra 2011-12-24 07:18:08

+0

我終於找出問題它與我正在使用的路徑有關。我需要定義一個絕對路徑: $ absolutepath = $ _SERVER {'DOCUMENT_ROOT'}。'wp-content/gallery/playerphotos /'。 $ photoname。名爲.jpg; file_exists函數現在可以正常工作。 ;) – DoubleA 2012-01-06 01:30:15

0

在PHP中,我們可以得到在雙引號也變量的值。在路徑中使用雙引號是一種很好的做法,因此不需要太多縮進。

$playerfileLocation = "../wp-content/gallery/playerphotos/$playerid.jpg"; 


$default_player = "../wp-content/gallery/playerphotos/default.jpg"; 
if(!file_exists($playerfileLocation)) 
{ 
$playerfileLocation=$default_player; 
} 
1

您的代碼拼寫錯誤:(不存在退出)

$playerfileLocation = "../wp-content/gallery/playerphotos/$playerid.jpg"; 

$default_player = "../wp-content/gallery/playerphotos/default.jpg"; 

if(file_exits($playerfileLocation)) 

{ 

} 

else 

{ 

$playerfileLocation=$default_player; 

} 
+0

現在我覺得自己像個白癡。 謝謝你解決我的問題。 – DoubleA 2011-12-24 04:39:11

相關問題