【问题标题】:Check file exist or not in PHP [duplicate]检查文件是否存在于PHP中[重复]
【发布时间】:2014-02-17 06:37:45
【问题描述】:

我想检查文件是否存在并显示定义的图像。我尝试使用如下代码。即使存在 1111.pdf,它也始终只显示 no.png!

$fileUrl = "http://localhost/Report/1111.pdf";
 $AgetHeaders = @get_headers($sourcePath);
 if (preg_match("|200|", $AgetHeaders[0])) {
 // file exists
echo "<img src='http://localhost/Report/yes.png'>";
 } else {
 // file doesn't exists
echo "<img src='http://localhost/Report/no.png'>";
 } 

【问题讨论】:

    标签: php


    【解决方案1】:

    你试过用谷歌搜索吗?

    file_exists function

    file_exists

    file_exists — 检查文件或目录是否存在

    bool file_exists (string $filename)

    例子:

    <?php
    $filename = '/path/to/foo.txt';
    
    if (file_exists($filename)) {
        echo "The file $filename exists";
    } else {
        echo "The file $filename does not exist";
    }
    ?>
    

    【讨论】:

    • 为什么它不适用于我的服务器! &lt;?php $file = 'http://localhost/Report/1.pdf'; if(file_exists($file)) { echo "&lt;img src='http://localhost/Report/yes.png'&gt;"; }else{ echo "&lt;img src='http://localhost/Report/no.png'&gt;"; }
    • “不工作”是什么意思?它给出了一个错误?什么?
    • 代码只显示“no.png”,即使文件“1.p​​df”存在!没有错误!
    • 尝试使用相对路径而不是绝对路径。
    • 相对路径可行!如何使用绝对路径?
    【解决方案2】:

    使用这个功能:-

    if (file_exists('filename')) {
     …do something
     }
    

    【讨论】:

    • 为什么它不适用于我的服务器! &lt;?php $file = 'http://localhost/Report/1.pdf'; if(file_exists($file)) { echo "&lt;img src='http://localhost/Report/yes.png'&gt;"; }else{ echo "&lt;img src='http://localhost/Report/no.png'&gt;"; }
    【解决方案3】:

    如果你想检查外部文件,你可以试试这个功能

    function curl_check_file_exist($url)
    {
         $rarr = array();
        $useragent = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent); //set our user agent
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    
       $header = substr($result, 0, $header_size);
       $result = substr($result, $header_size);
       $ok = $info['http_code'];
    
    
       if($ok == 200)
       {
         return true;
       }
       else
       {
        return false;
      }
     }
    

    喜欢这个

     if(curl_check_file_exist($url))
     {
        .....
    
     }
     else
     {
        .....
     }
    

    但我想查看本地文件

    file_exists(path) 
    

    功能不错

    【讨论】:

      猜你喜欢
      • 2011-05-14
      • 2018-12-26
      • 2014-05-03
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多