Conditional include

They have: 3 posts

Joined: Jun 2009

I'd like to create a conditional include that will display content only if the include file is present.

Here's my include as it is scripted now:

<?php
// import file
include("wp-content/plugins/stuff.inc");
?>

How would I add a conditional statement that would display nothing if stuff.inc is not present?

Thanks

He has: 698 posts

Joined: Jul 2005

Something like this:

<?php
$file
= "wp-content/plugins/stuff.inc"
if (file_exists($file)) {
  include(
$file);
}
?>

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Or if you don't want anything "at all" to happen if the file is not included and stop the entire page load and rest of script, use this:

<?php
if (!include('wp-content/plugins/stuff.inc')){
exit(
'file not available');
}
?>

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

Isn't that the definition of require? It stops execution of the script if the file isn't available.

<?php
@include 'wp-content/plugins/stuff.inc';
?>

might achieve the desired result. The @ symbol will suppress the warning that is produced if the file is not available.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

teammatt3 wrote:
Isn't that the definition of require?
It is, but using a PHP E_ERROR halts the script and doesn't allow for a friendly message, just a white screen.
Include() only issues an E_WARNING, allowing a message and rest of page, or as my example with an exit.

Ideally you would include the header/content/footer/navigation etc with a message then exit() if desired, or "other" criteria if the file was not available.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.