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

时间:2012-04-23 13:42:42

标签: php

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

http://www.stackoverflow.com/favicon.ico
http://www.stackoverflow.com/reset.css

然后下载它(如果显然是exixts)。

2 个答案:

答案 0 :(得分:5)

<?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.";
}

答案 1 :(得分:1)

试试这个:

<?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 );
?>

希望这有帮助。