我想在php中检查url http://example.com/file.txt
是否存在。我该怎么做?
我想在php中检查url http://example.com/file.txt
是否存在。我该怎么做?
if(! @ file_get_contents('http://www.domain.com/file.txt')){
echo 'path doesn't exist';
}
这是最简单的方法。如果您不熟悉@
,它将指示该函数在原本会抛出错误的情况下返回false。
@!
或 !@
更好?我使用前者,对后者感到有些奇怪——也许是因为在操作符之后加上 @
感觉不应该有效,尽管显然应该。 - Tortoise@
并且它失败了,它将返回 0
而不是 false
- 你可以用 if
来测试它是否为 falsey 或者 ===0
但不是 ===false
。 - doublesharp使用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
我同意这个回复,我通过这样做取得了成功。
$url = "http://example.com/file.txt";
if(! @(file_get_contents($url))){
return false;
}
$content = file_get_contents($url);
return $content;
在PHP中尝试Ping网站并返回结果的函数。
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;
}
}
$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";
}