简体   繁体   中英

php include file only if existing

I'm testing some caching code in php:

   if (is_readable($cachefile) && (time() - $cachetime
     < filemtime($cachefile))) 
  {
            include($cachefile);
   […]

What it should do: Run include only if $cachefile already exists. If not it's supposed to proceed without trying to include $cachefile.

What it does: It tries to load $cachefile every time therefore creating a php warning when it does not exist.

I have no idea how to fix it since I tried just about everything that would normally prevent include from being excecuted. Can someone help?
Thanks!

if(file_exists('file.php'))包括'file.php';

Try like this

if (isset($cachefile) && ((time() - $cachetime) < filemtime($cachefile))) 
{
    include($cachefile);
}

you can use isset or file_exists functions, here is documentations =>

http://php.net/manual/en/function.file-exists.php

http://php.net/manual/en/function.isset.php

Note : Wrap time() - $cachetime in () , also make sure $cachefile 's url is right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM