Emanuil Rusev
Emanuil Rusev

Reputation: 35265

How to include a file only if the file exists in PHP?

I need an include function / statement that will include a file only if it exists. Is there one in PHP?

You might suggest using @include but there is an issue with that approach - in case the file to be included exists, PHP will not output warnings if the parser find something wrong in the included file.

Upvotes: 54

Views: 58564

Answers (10)

Jesse Nickles
Jesse Nickles

Reputation: 1849

I'm posting these as an answer since they were discussed in comments:

if(is_file($file)) {
  include $file;
}

Or:

is_file($file) AND include $file;

This is theoretically faster and also safer than using file_exists because it skips right to using the simple test is_file without having to check whether it's a file vs folder, etc, and it also will never load a folder (potentially unsafe).

Here's a brief example:

<?php
$file = "test.txt";
if(is_file($file)) {
  echo ("$file is a regular file");
} else {
  echo ("$file is not a regular file");
}
?>

Ref: https://www.w3schools.com/php/func_filesystem_is_file.asp

Upvotes: 1

valiD
valiD

Reputation: 359

@include($file);

Using at in front, ignores any error that that function might generate. Do not abuse this as IT IS WAY SLOWER than checking with if, but it is the shortest code alternative.

Upvotes: 3

Abdul Gaffar Shah
Abdul Gaffar Shah

Reputation: 45

function get_image($img_name) {
    $filename = "../uploads/" . $img_name;
    $file_exists = file_exists($filename);
    if ($file_exists && !empty($img_name)) {
        $src = '<img src="' . $filename . '"/>';
    } else{
        $src = '';
    }
    return $src;
}
echo get_image($image_name);

Upvotes: -2

Nickkk
Nickkk

Reputation: 2647

Based on @Select0r's answer, I ended up using

if (file_exists(stream_resolve_include_path($file)))
    include($file);

This solution works even if you write this code in a file that has been included itself from a file in another directory.

Upvotes: 8

Stephane JAIS
Stephane JAIS

Reputation: 1433

Check out the stream_resolve_include_path function.

Upvotes: 3

oezi
oezi

Reputation: 51817

Try using file_exists()

if(file_exists($file)){
  include $file;
}

Upvotes: 9

Floern
Floern

Reputation: 33904

the @ suppresses error messages.

you cloud use:

$file = 'script.php';
if(file_exists($file))
  include($file);

Upvotes: 0

JP19
JP19

Reputation:

I think you have to use file_exists, because if there was such an include, it would have been listed here: http://php.net/manual/en/function.include.php

Upvotes: 1

Colum
Colum

Reputation: 3914

if(file_exists('file.php'))
    include 'file.php';

That should do what you want

Upvotes: 103

Select0r
Select0r

Reputation: 12668

How about using file_exists before the include?

Upvotes: 3

Related Questions