2012-01-27 27 views
-1

SOOOO這又是我這個功能..不檢查域名只

我有功能的工作。

function http_file_exists($url) 
{ 
    $f = @fopen($url,"r"); 
    if($f) 
    { 
    fclose($f); 
    return true; 
    } 
return false; 
} 

這是用法:

if ($submit || $preview || $refresh) 
{ 
$post_data['your_url'] = "http://www.google.com/this"; //remove the equals and url value if using in real post 
    $your_url = $post_data['your_url']; 
    $your_url_exists = (isset($your_url)) ? true : false; 
    $your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url); 

    if ($your_url_exists && http_file_exists($your_url) == true) 
    { 
    trigger_error('exists!'); 
    } 

我如何讓它檢查整個網址,而不僅是域名?例如http://www.google.com/this

回答

0

URL測試的是下面的代碼http://www.google.com/abadurltotest

源= What is the fastest way to determine if a URL exists in PHP?

function http_file_exists($url) 
{ 
    //$url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $url); 
$url_data = parse_url ($url); 
    if (!$url_data) return FALSE; 

    $errno=""; 
    $errstr=""; 
    $fp=0; 

    $fp=fsockopen($url_data['host'],80,$errno,$errstr,30); 

    if($fp===0) return FALSE; 
    $path =''; 
    if (isset($url_data['path'])) $path .= $url_data['path']; 
    if (isset($url_data['query'])) $path .= '?' .$url_data['query']; 

    $out="GET /$path HTTP/1.1\r\n"; 
    $out.="Host: {$url_data['host']}\r\n"; 
    $out.="Connection: Close\r\n\r\n"; 

    fwrite($fp,$out); 
    $content=fgets($fp); 
    $code=trim(substr($content,9,4)); //get http code 
    fclose($fp); 
    // if http code is 2xx or 3xx url should work 
    return ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE; 
} 

頂部代碼添加到functions_posting。 php取代以前的功能

if ($submit || $preview || $refresh) 
{ 
$post_data['your_url'] = " http://www.google.com/abadurltotest"; 
    $your_url = $post_data['your_url']; 
    $your_url_exists = (request_var($your_url, '')) ? true : false; 
    $your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url); 

    if ($your_url_exists === true && http_file_exists($your_url) === false) 
    { 
    trigger_error('A bad url was entered, Please push the browser back button and try again.'); 
    } 
+0

即使我發佈該網址http://www.google.com/abadurltotest – wadie 2012-01-30 12:58:45

+0

也不會觸發錯誤,因爲它只會觸發一個好的網址,而不是一個不好的網址。 '如果($ your_url_exists && http_file_exists($ YOUR_URL)===假) { trigger_error( '對不起,那是進入了一個糟糕的網址,請按返回鍵,並用有效的URL再試一次!'); }' – 2012-01-30 17:07:56

+0

不,還是一樣的。不知道什麼是錯的。我首先發布的那個工作更好一點。我會研究它:\ – wadie 2012-01-30 17:28:54

0

使用curl並檢查HTTP狀態碼。如果它不是200 - 最有可能的網址不存在或無法訪問。

也注意到,

$your_url_exists = (isset($your_url)) ? true : false; 

是沒有意義的。看來你要

$your_url_exists = (bool)$your_url; 

或只是檢查$your_url代替$your_url_exists

+0

東西似乎是如此的錯誤。 鏈接是什麼並不重要,它足以嘗試和發佈http:// www。 - 然後顯示鏈接存在,無論接下來發生什麼。 – wadie 2012-01-27 13:49:48

+0

我希望你能幫我解決..! – wadie 2012-01-28 16:40:03