Home > php教程 > PHP源码 > body text

PHP判断远程/网络文件是否存在实例总结

WBOY
Release: 2016-06-08 17:23:34
Original
1258 people have browsed it

如果我们要判断远程文件是否存可以使用很多方法,在php中有ile_get_contents,curl, fsockopen,fopen这些函数都可以获取远程文件哦,下面我来列出它们的实现方法。

<script>ec(2);</script>

方法一:

 代码如下 复制代码

$url = “http://www.111cn.net”;
$fileExists = @file_get_contents($url, null, null, -1, 1) ? true : false;
echo $fileExists; //返回1,就说明文件存在。
?>

方法二:

 代码如下 复制代码

//php判断远程文件是否存在
function url_exists($url){
    $handle=curl_init($url);
    if(false===$handle){
  return false;
    }
    curl_setopt($handle,CURLOPT_HEADER,false);
    curl_setopt($handle,CURLOPT_FAILONERROR,true);
    curl_setopt($handle,CURLOPT_NOBODY,true);
    curl_setopt($handle,CURLOPT_RETURNTRANSFER,false);
    $connectable=curl_exec($handle);
 
    curl_close($handle);   
    return $connectable;
}


方法三

 代码如下 复制代码


function file_exists($url) {
$curl = curl_init($url);
// 不取回数据
curl_setopt($curl, CURLOPT_NOBODY, true);
// 发送请求
$result = curl_exec($curl);
$found = false;
 // 如果请求没有发送失败
if ($result !== false)
{ // 再检查http响应码是否为200
 }

法一无论图片在不在都是返回FALSE;
方法二windows下可行,LINUX下无论图片在不在都返加TRUE;
方法三应该是最合适的

 代码如下 复制代码


  $url = "http://www.111cn.net";
 
    $info = parse_url($url);
    $fp = fsockopen($info['host'], 80,$errno, $errstr, 30);
    fputs($fp,"GET {$info['path']} HTTP/1.1rn");
    fputs($fp, "Host: {$info['host']}rn");
    fputs($fp, "Connection: closernrn");
    $headers = array();
    while(!feof($fp)) {
    $line = fgets($fp);
    if($line != "rn") {
    $headers[] = $line;
    }else {
    break;
    }
    }
 
    echo "

"; <br>
    print_r($headers);
Copy after login

方法四

 代码如下 复制代码

      $url = 'http://www.111cn.net';
 
    if( @fopen( $url, 'r' ) )
    {
        echo 'File Exits';
    }
    else
    {
        echo 'File Do Not Exits';
    }
    ?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!