检查php中的下载链接是否失效


Check if download link is dead in php?

如果我得到页面的标题,我可以告诉下载链接是有效的还是无效的。

例如:"Free online storage"为死链接的标题,"[文件名]"为活动链接的标题(mediafire)。但是我的页面需要很长时间来响应,所以有没有其他的方法来检查下载链接是有效的还是无效的?

这就是我所做的:

<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
    preg_match("/'<title'>(.*)'<'/title'>/",$str,$title);
    return $title[1];
}
}
?>

不执行GET请求,它下载整个页面/文件,而是执行HEAD请求,它只获取HTTP头,并检查状态是否为200,内容类型是否为text/html

像这样…

function url_validate($link)
{
    #[url]http://www.example.com/determining-if-a-url-exists-with-curl/[/url]
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $link);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); //follow up to 10 redirections - avoids loops
    $data = curl_exec($ch);
    curl_close($ch);
    preg_match_all("/HTTP'/1'.[1|0]'s('d{3})/",$data,$matches);
    $code = end($matches[1]);
    if(!$data) 
    {
        return(false);
    } 
    else 
    {
        if($code==200) 
        {
            return(true);
        } 
        elseif($code==404) 
        {
            return(false);
        }
    }
}

您可以安全地使用任何cURL库函数。这是合法的,因此不会被视为黑客攻击。唯一的要求是你的虚拟主机公司安装了cURL扩展,这是很有可能的。

cURL应该做这项工作。如果需要,还可以检查返回的标题和文本内容。