You are viewing this site as a guest. Join our community to get your questions answered and share knowledge. Active members may advertise and ask for a website critique.

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: 670 posts

Joined: Jul 2005

Something like this:

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

He has: 1,580 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');
}
?>

Signature links on this forum are NO-follow! - This means spam is futile!

teammatt3's picture

He has: 2,076 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.

He has: 1,580 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.

Signature links on this forum are NO-follow! - This means spam is futile!