【发布时间】:2012-10-24 22:52:15
【问题描述】:
我想查看网址
http://example.com/file.txt
php中存在与否。我该怎么做?
【问题讨论】:
标签: php url file-exists
我想查看网址
http://example.com/file.txt
php中存在与否。我该怎么做?
【问题讨论】:
标签: php url file-exists
我同意这个回复,我这样做成功了
$url = "http://example.com/file.txt";
if(! @(file_get_contents($url))){
return false;
}
$content = file_get_contents($url);
return $content;
您可以按照代码检查该文件是否存在于该位置。
【讨论】:
if(! @ file_get_contents('http://www.domain.com/file.txt')){
echo 'path doesn't exist';
}
这是最简单的方法。如果您不熟悉@,它将指示函数返回 false,否则会引发错误
【讨论】:
@! 还是!@ 是否有普遍共识?我使用前者,但出于某种原因对后者感到很奇怪——也许 @ after 操作员觉得它不应该工作,即使它显然应该工作。
@ 并且它失败了,它将返回0,而不是false - 您可以使用if 对其进行测试,因为它是错误的,或者===0但不是===false。
$filename="http://example.com/file.txt";
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
或
if (fopen($filename, "r"))
{
echo "File Exists";
}
else
{
echo "Can't Connect to File";
}
【讨论】:
在Ping site and return result in PHP 上试试这个功能。
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
【讨论】:
将使用 PHP curl 扩展:
$ch = curl_init(); // set up curl
curl_setopt( $ch, CURLOPT_URL, $url ); // the url to request
if ( false===( $response = curl_exec( $ch ) ) ){ // fetch remote contents
$error = curl_error( $ch );
// doesn't exist
}
curl_close( $ch ); // close the resource
【讨论】: