How to include only if file exists

Php

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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

That should do what you want

Solution 2 - Php

Try using file_exists()

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

Solution 3 - Php

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.

Solution 4 - Php

How about using file_exists before the include?

Solution 5 - Php

Check out the stream_resolve_include_path function.

Solution 6 - Php

@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.

Solution 7 - Php

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

Solution 8 - Php

the @ suppresses error messages.

you cloud use:

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

Solution 9 - Php

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);

Solution 10 - Php

<?php  
  if(file_exists('file.php'))
        include 'file.php';
    }else{
    	header("Location: http://localhost/);
    	exit;
    
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEmanuil RusevView Question on Stackoverflow
Solution 1 - PhpColumView Answer on Stackoverflow
Solution 2 - PhpoeziView Answer on Stackoverflow
Solution 3 - PhpNickkkView Answer on Stackoverflow
Solution 4 - PhpSelect0rView Answer on Stackoverflow
Solution 5 - PhpStephane JAISView Answer on Stackoverflow
Solution 6 - PhpvaliDView Answer on Stackoverflow
Solution 7 - PhpJP19View Answer on Stackoverflow
Solution 8 - PhpFloernView Answer on Stackoverflow
Solution 9 - PhpAbdul Gaffar ShahView Answer on Stackoverflow
Solution 10 - PhpLiang LeeView Answer on Stackoverflow