2012-05-03 21 views
3

我試圖檢查gravatar是否存在。當我嘗試在先前的問題中推薦的方法時,出現錯誤「Warning:get_headers()[function.get-headers]:該函數只能用於URL」任何人看到這個或看到我的代碼中的錯誤? PS我不想爲gravatar指定一個默認圖片,因爲如果沒有gravatar退出,可能會有多個默認圖片。php檢查gravatar是否存在標題錯誤

此外,我發現一個錯誤的參考可能與我的ini文件有關,我認爲我的主機不允許我訪問該文件。如果是這樣,是否有替代getheaders?非常感謝。

$email = $_SESSION['email']; 
$email= "[email protected]"; //for testing 
$gravemail = md5(strtolower(trim($email))); 
$gravsrc = "http://www.gravatar.com/avatar/".$gravemail; 
$gravcheck = "http://www.gravatar.com/avatar/".$gravemail."?d=404"; 
$response = get_headers('$gravcheck'); 
echo $response; 
exit; 
if ($response != "404 Not Found"..or whatever based on response above){ 
$img = $gravsrc; 
} 
+0

鬆散約$ gravcheck撇號,否則它只是包含「$ gravcheck」的字符串,而不是變量的內容:'get_headers($ gravcheck);' – Niko

+0

非常感謝這個catch..it導致錯誤。 – user1260310

回答

10

觀察

A. get_headers('$gravcheck');不會因爲使用單引號的工作'

B.調用exit;將終止腳本過早

C. $response會返回一個數組,你可以不使用echo打印信息使用print_r insted

D. $response != "404 Not Found"是行不通的,因爲$response是陣列

這是做正確的方法:

$email= "[email protected]"; //for testing 
$gravemail = md5(strtolower(trim($email))); 
$gravsrc = "http://www.gravatar.com/avatar/".$gravemail; 
$gravcheck = "http://www.gravatar.com/avatar/".$gravemail."?d=404"; 
$response = get_headers($gravcheck); 
print_r($response); 
if ($response[0] != "HTTP/1.0 404 Not Found"){ 
    $img = $gravsrc; 
} 
+2

第一個響應索引現在包含字符串「HTTP/1.1 404 Not Found」。我個人使用'strpos($ response [0],「404 Not Found」)=== false'來確定頭部響應是否有效,但總的來說,這是一個明確檢查404 。 – maiorano84