首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何知道某个资源是否存在?

如何知道某个资源是否存在?
EN

Stack Overflow用户
提问于 2012-04-23 21:42:42
回答 2查看 1.1K关注 0票数 0

例如,我想知道这些文件是否存在。

代码语言:javascript
复制
http://www.stackoverflow.com/favicon.ico
http://www.stackoverflow.com/reset.css

然后下载它(如果明显存在)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-23 21:46:02

代码语言:javascript
复制
<?php

if( ( $file = file_get_contents( 'http://www.stackoverflow.com/favicon.ico' ) ) ) {
    echo "file exists.";
    file_put_contents( 'favicon.ico', $file );
}
else {
    echo "File does not exist.";
}
票数 5
EN

Stack Overflow用户

发布于 2012-04-23 21:54:01

试试这个:

代码语言:javascript
复制
<?php
$ch = curl_init();

$url    = 'YOUR_URL_HERE'; // the url you want to check

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $ch, CURLOPT_USERAGENT, $_SERVER[ 'HTTP_USER_AGENT' ] );

// make "HEAD" request
curl_setopt( $ch, CURLOPT_HEADER, true );
curl_setopt( $ch, CURLOPT_NOBODY, true );

$res    = curl_exec( $ch );
$res    = explode( ' ', substr( $res, 0, strpos( $res, "\n" ) ) );

// if 404, file does not exist
if( $res[ 1 ] != 404 ) {
    $file = file_get_contents( $url ); 
} else {
    // This url does not exist
    $file = '';
}

curl_close( $ch );
?>

希望这能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10281742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档