免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1627 | 回复: 1

PHP检查文件是否在不同域名下的存在情况 [复制链接]

论坛徽章:
0
发表于 2012-01-07 10:48 |显示全部楼层
PHP检查文件是否在不同域名下的存在情况








Earlier today I needed to find out if a file exists on a different domain. Initially I used the file_exists function, but then when that threw back an error I remembered that file_exists only checks whether a file or directory exists on the same server as the script.

After I played around with various functions, I came up with a few lines of code that actually works:

How to check if file exists on a different domain
Php代码
  1. <?   
  2. $image = "http://www.example.co.uk/images/1.jpg";   
  3. $handle = @fopen("$image", "r");   
  4. if(strpos($handle, "Resource id") !== false)   
  5. {   
  6. echo "file does exist";   
  7. }   
  8. else  
  9. {   
  10. echo "file does not exist";   
  11. }   
  12. ?>  

  13. <?
  14. $image = "http://www.example.co.uk/images/1.jpg";
  15. $handle = @fopen("$image", "r");
  16. if(strpos($handle, "Resource id") !== false)
  17. {
  18. echo "file does exist";
  19. }
  20. else
  21. {
  22. echo "file does not exist";
  23. }
  24. ?>  
复制代码
The logic explained
Ok, so if the file exists (1.jpg) the fopen function will throw back a “resource id” response. So I check the response to see if “response id” exists with the strpos function. It’s really as simple as that.

I’m not entirely sure if my method is the best, nor the most efficient, but it seems to work pretty well, and I can’t think of any other methods. Anyone know of any other/better methods?

Better solution
Thanks to a comment left by Paul I’ve been made aware of a better solution.



Php代码
  1. $url = "http://www.example.com/index.php";   
  2. $header_response = get_headers($url, 1);   
  3. if ( strpos( $header_response[0], "404" ) !== false )   
  4. {   
  5.   // FILE DOES NOT EXIST   
  6. }   
  7. else   
  8. {   
  9.   // FILE EXISTS!!   
  10. }  
复制代码

论坛徽章:
0
发表于 2012-01-07 10:48 |显示全部楼层
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP