2012-01-27 43 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