V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
kasp
V2EX  ›  PHP

is_file和file_exists的区别

  •  
  •   kasp · 2013-05-27 17:02:45 +08:00 · 3731 次点击
    这是一个创建于 3986 天前的主题,其中的信息可能已经有所发展或是发生改变。
    把标题放到GOOGLE里搜索,出来的结果都是关于二者读写速度的介绍,没有人提到结果上的不同,我遇到了。
    情景介绍:
    在开发环境下挂载开发人员的机器共享来实现程序的读取使用
    开发人员A是XP系统于是就出现挂载成功但文件判断存在失败的情况。
    将is_file换成file_exists一切恢复。
    使用linux samba共享的未出现此问题。
    原理未知。。。
    10 条回复    1970-01-01 08:00:00 +08:00
    imcaibaozi
        1
    imcaibaozi  
       2013-05-27 17:18:34 +08:00
    is_file() will return false if the given path points to a directory. file_exists() will return true if the given path points to a valid file or directory.

    http://stackoverflow.com/questions/792899/is-file-or-file-exists-in-php
    kasp
        2
    kasp  
    OP
       2013-05-27 17:27:35 +08:00
    同样是文件的情况下。
    @imcaibaozi
    kasp
        3
    kasp  
    OP
       2013-05-27 17:35:08 +08:00
    $xpf = dirname(dirname(__FILE__)).'/works/xpf';//xpf目录是XP共享,通过mount挂载到linux目录
    $r = $xpf.'/config/cache.php';
    var_dump(file_exists($r));//true
    var_dump(is_file($r));//false
    imcaibaozi
        4
    imcaibaozi  
       2013-05-27 18:53:03 +08:00
    is_link() 呢?
    vietor
        5
    vietor  
       2013-05-27 19:05:01 +08:00
    猜想is_file读了file attributes来判断类型,应该比file_exists慢
    Feobe
        6
    Feobe  
       2013-05-27 21:41:21 +08:00
    php::is_file
    ————————————-
    total self: 0.5ms
    total cum: 0.5ms
    calls: 10,000
    php::file_exists
    ————————————-
    total self: 41ms
    total cum: 41ms
    calls: 10,000
    is_file却快了N倍

    在php底层源码里,也确是这样
    @vietor
    fatpa
        7
    fatpa  
       2013-05-28 00:59:54 +08:00
    一个判断文件是否存在,一个判断是否为文件吧……
    vietor
        8
    vietor  
       2013-05-28 08:57:35 +08:00
    @Feobe 的确我错了。
    之前我考察过这两个函数,我忘记了结论。经过你的数据,可以想起一部分:file attributes验证文件存在的方式最快,file_exists好像调用了别的处理,是什么想不起来了。
    imcaibaozi
        9
    imcaibaozi  
       2013-05-28 11:36:29 +08:00
    @kasp 最后到底是因为什么呢@@
    kasp
        10
    kasp  
    OP
       2013-05-28 19:17:42 +08:00
    @imcaibaozi 不知道呢,应该需要读下PHP源码看下两个函数实现的方式有什么区别吧。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5556 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:06 · PVG 11:06 · LAX 20:06 · JFK 23:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.