2014-12-27 40 views
0

好吧,所以我正在製作一個腳本來檢查給定的網站是否返回403。我加入了一些小部件以實現這一目標,如果我一次只檢查一個網站,但它並不適用於多個網站,那麼它確實有效。使用cURL,爆炸和foreach檢查403響應代碼

$url = $_POST['site']; 

$many_urls = explode(",", $url); 

$handle = curl_init($url); 
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); 

/* Get the HTML or whatever is linked in $url. */ 
$response = curl_exec($handle); 

/* Check for 403 (forbidden). */ 
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); 

foreach ($many_urls as $urls) 
{ 
    if($httpCode == 403) { 
     echo "<h2>$url is <font color='red'>Forbidden.</font><h2>"; 
    } else echo "<h2>$url <font color='green'>Works.</font><h2>"; 
} 

curl_close($handle); 

所以,如果我例如輸入:google.com,youtube.com,forbiddenwebsite.com

它應該返回:

google.com 工作 youtube.com Works forbiddenwebsite.com is Forbidden(在不同的線路上)

我很確定foreach部分存在問題。

任何幫助,將不勝感激。謝謝。

回答

0

如果您要在列表形式中獨立檢查每個URL,則需要在循環中具有該捲曲。否則,您正在檢查「google.com,youtube.com,forbiddenwebsite.com」的標題,這不是有效的地址。試試這個:

/* exploding the url list will give an array with 1 item in the case of only 1 url */ 
$urls = explode(',', $_POST['site']); 

/* wrap the whole thing in the loop, check each url individually */ 
foreach($urls as $url){ 

    $handle = curl_init($url); 
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); 

    /* Get the HTML or whatever is linked in $url. */ 
    $response = curl_exec($handle); 

    /* Check for 403 (forbidden). */ 
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); 

    if($httpCode == 403) { 
     echo "<h2>$url is <font color='red'>Forbidden.</font><h2>"; 
    } else echo "<h2>$url <font color='green'>Works.</font><h2>"; 


    curl_close($handle); 
} 

你可能會想添加某種檢查在後傳遞一個空字符串的情況下,也瓦爾。

+0

哇這個工作!非常感謝。現在有辦法讓這件事情變得更好或更快嗎? –

+0

如果您要查找的只是頭文件的響應代碼,您可以查看['get_headers'函數](http://php.net/manual/en/function.get-headers.php) – aviemet