MENU

php 判断文件是否存在

• October 2, 2017 • Read: 31 • PHP

对于本地服务器文件:

<?php
$url = 'usr/themes/Themia/img/sj/85.jpg';
if( file_exists($url) )
{
 echo '存在';
}
else
{
  echo '不存在';
}
?>

对于远程文件的判断:

fopen() 方法:

<?php
    $url = 'http://qqdie.com/test.jpg';
 
    if( @fopen( $url, 'r' ) )
    {
        echo '存在';
    }
    else
    {
        echo '不存在';
    }
    ?>

CURL 方法:

<?php
    $url2 = 'http://www.qqdie.com/test.jpg';
 
    $ch = curl_init();
    $timeout = 10;
    curl_setopt ($ch, CURLOPT_URL, $url2);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 
    $contents = curl_exec($ch);
    //echo $contents;
    if (preg_match("/404/", $contents)){
        echo '文件不存在';
    }
    ?>
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code