我尝试使用file_exists(URL/robots.txt)来查看该文件是否存在于随机选择的网站上,并得到错误的回复;
如何检查robots.txt文件是否存在?
在我检查之前,我不想开始下载.
使用fopen()可以解决问题吗?因为:成功时返回文件指针资源,错误时返回FALSE.
我想我可以把这样的东西:
$f=@fopen($url,"r");
if($f) ...
Run Code Online (Sandbox Code Playgroud)
我的代码:
http://www1.macys.com/robots.txt 也许它不存在 http://www.intend.ro/robots.txt 也许它不存在 http://www.emag.ro/robots.txt 也许它不是那里 http://www1.bloomingdales.com/robots.txt 也许它不存在
try {
if (file_exists($file))
{
echo 'exists'.PHP_EOL;
$curl_tool = new CurlTool();
$content = $curl_tool->fetchContent($file);
//if the file exists on local disk, delete it
if (file_exists(CRAWLER_FILES . 'robots_' . $website_id . '.txt'))
unlink(CRAWLER_FILES . 'robots_' . $website . '.txt');
echo CRAWLER_FILES . 'robots_' . $website_id . '.txt', $content . PHP_EOL;
file_put_contents(CRAWLER_FILES . 'robots_' . $website_id . '.txt', $content);
}
else
{
echo 'maybe it\'s not there'.PHP_EOL;
}
} catch (Exception $e) {
echo 'EXCEPTION ' . $e . PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)
file_exists不能用于其他网站上的资源.它适用于本地文件系统.看看这里关于如何正确进行检查.
正如其他人在评论中提到的那样,链接说它(可能)最容易使用get_headers函数来执行此操作:
try {
if (strpos(get_headers($url,1),"404")!==FALSE){
... your code ...
} else {
... you get the idea ...
}
}
Run Code Online (Sandbox Code Playgroud)