PHP File Include With Custom Error Message

Started by Mark, October 06, 2009, 01:38:21 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Mark

If you are manually creating a lightweight website template you may come across something on your site that you wish to have throughout the website such as a navigation menu or even just the theme as a whole. While bigger websites or website scripts will probably use a MySQL database in conjunction with a fancy template for this, if you're not familiar with DB's then it's probably going to be confusing for you when you create your website. Or. on the other hand, if it's a relatively small website then you may not want to use a DB at all.

You do have another, simple tool at your disposal. You'll want to use what's called Server Side Include or SSI. That way, if you need to add something to your sidebar or theme, you can change the one file and it will change across your website.

So, the basics. When you want to include a file you simply use the following function:
<?php include('/home/YOURACCOUNT/public_html/includes/sidebar.php'); ?>

This works perfectly fine, however, if you move or or otherwise accidentally delete the file you're calling you'll get that ugly PHP error message that also shows your file path containing your username which is bad. Even if you have a very strong password, it's a good idea to keep it from showing. So, how do we do this?

We use an if statement that looks for the file. This basically says if the file is there, load it. However, if it's not, show a customized message:
<?php
if(
file_exists('/home/YOURACCOUNT/public_html/includes/sidebar.php'))
include('/home/YOURACCOUNT/public_html/includes/sidebar.php');
else
echo'Sidebar failed to load.';
?>


Now, if the file is missing it will instead show the message "Sidebar failed to load.". Of course, you can change this to whatever you like. I prefer "Your overzealous website admin got TOO excited.". :P

Enjoy.

Jason

Cool -- I may give that a shot as I use includes like crazy.  Nothing like changing one file vs. 100's when you need to do something.

As for the include path, I don't use the full server path in mine.  I think there are some restrictions but I use them formatted like:

<?php include("filename.xxx"); ?>

which works fine if they're in the same directory. 

Mark

#2
I think, because of the if statement (I could be wrong as I don't know PHP that well) you have to put the full path. Either that or if it's not in the same directory it doesn't like it.

I tried switching it to "/includes/sidebar.php" (note the ' changed to ") and it didn't work.

Also, I tried leaving the file_exists with the full path and the include with the short path and that still didn't work.

Jason

You're probably right.  I have duplicated the includes a few times when directory structures have caused me issues.