PHP判断远程路径是否存在

来源:互联网 发布:真维斯淘宝店模特名字 编辑:程序博客网 时间:2024/06/05 18:04

方法一(需要开启allow_url_fopen):


1<?php
2    $url="http://http://github.codeigniter.org.cn/download/CodeIgniter_2.1.2.zip";
3    $fileExists= @file_get_contents($url, null, null, -1, 1) ? true : false;
4    echo$fileExists;//返回1,就说明文件存在。
5?><B> </B>

方法二(需要服务器支持Curl组件):


01<?php
02function check_remote_file_exists($url) {
03    $curl= curl_init($url);// 不取回数据
04    curl_setopt($curl, CURLOPT_NOBODY, true);
05    curl_setopt($curl, CURLOPT_CUSTOMREQUEST,'GET');// 发送请求
06    $result= curl_exec($curl);
07    $found= false;// 如果请求没有发送失败
08    if($result!== false) {
09  
10        /** 再检查http响应码是否为200 */
11        $statusCode= curl_getinfo($curl, CURLINFO_HTTP_CODE);
12        if($statusCode== 200) {
13            $found= true;
14        }
15    }
16    curl_close($curl);
17  
18    return$found;
19}
20  
21$url = "http://github.codeigniter.org.cn/download/CodeIgniter_2.1.2.zip";
22echo check_remote_file_exists($url);// 返回1,说明存在。
23  
24?>



01<?php
02  
03/*
04 函数:remote_file_exists
05 功能:判断远程文件是否存在
06 参数: $url_file -远程文件URL
07 返回:存在返回true,不存在或者其他原因返回false
08*/
09function remote_file_exists($url_file){
10    //检测输入
11    $url_file= trim($url_file);
12    if(empty($url_file)) {return false; }
13    $url_arr=parse_url($url_file);
14    if(!is_array($url_arr) ||empty($url_arr)){returnfalse; }
15  
16    //获取请求数据
17    $host=$url_arr['host'];
18    $path=$url_arr['path'] ."?".$url_arr['query'];
19    $port= isset($url_arr['port']) ?$url_arr['port'] :"80";
20  
21    //连接服务器
22    $fp=fsockopen($host,$port,$err_no,$err_str,30);
23    if(!$fp){returnfalse; }
24  
25    //构造请求协议
26    $request_str="GET ".$path."HTTP/1.1\r\n";
27    $request_str.="Host:".$host."\r\n";
28    $request_str.="Connection:Close\r\n\r\n";
29  
30    //发送请求
31    fwrite($fp,$request_str);
32    $first_header=fgets($fp, 1024);
33    fclose($fp);
34  
35    //判断文件是否存在
36    if(trim($first_header) ==""){returnfalse;}
37    if(!preg_match("/200/",$first_header)){
38        returnfalse;
39    }

1<P><STRONG>函数描述及例子</STRONG></P>
2<P></P>
3<PRE class="brush:php; toolbar: true; auto-links: true;"><?
4    //测试代码
5    $str_url='http://127.0.0.2/getfile.php?id=404';
6    $exits= remote_file_exists($str_url);
7    echo$exists?"存在":"不存在";
8?><B> </B></PRE><B><BR>
9</B><P></P>
附送一个JS的判断


01<script  language="网页特效 "
02function   geturl(url) 
03
04        var   xmlhttp   =   new   activexobject( "microsoft.xmlhttp "); 
05        xmlhttp.open( "get ",url,false); 
06        xmlhttp.send(); 
07        if   (xmlhttp.readystate==4) 
08            alert((xmlhttp.status==200)? "文件存在 ": "文件不存在 "); 
09
10</script
11请输入文件地址: <input  name="file "  id="file "  value="http://www.111cn.net "
12<button  onclick="geturl(file.value) "> 检测地址 </button>