Jump to content

When to use "include" and when to use "include_once" ?


scanreg

Recommended Posts

I'm trying to understand when to use "include" and when to use "include_once" in an index file that pulls pieces together (same for "require" and "require_once").

 

For example, here is the current way an index.php file looks (snippet):

 

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';

if (isset($_GET['addjoke']))
{
include 'form.html.php';
exit();
}

if (isset($_POST['joketext']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

$joketext = mysqli_real_escape_string($link, $_POST['joketext']);
$sql = 'INSERT INTO joke SET
		joketext="' . $joketext . '",
		jokedate=CURDATE()';
if (!mysqli_query($link, $sql))
{
	$error = 'Error adding submitted joke: ' . mysqli_error($link);
	include 'error.html.php';
	exit();
}

header('Location: .');
exit();
}

if (isset($_GET['deletejoke']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

$id = mysqli_real_escape_string($link, $_POST['id']);
$sql = "DELETE FROM joke WHERE id='$id'";
if (!mysqli_query($link, $sql))
{
	$error = 'Error deleting joke: ' . mysqli_error($link);
	include 'error.html.php';
	exit();
}

header('Location: .');
exit();
}

 

Wouldn't this be more efficient like this? :

 

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';

include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

if (isset($_GET['addjoke']))
{
include 'form.html.php';
exit();
}

if (isset($_POST['joketext']))
{


$joketext = mysqli_real_escape_string($link, $_POST['joketext']);
$sql = 'INSERT INTO joke SET
		joketext="' . $joketext . '",
		jokedate=CURDATE()';
if (!mysqli_query($link, $sql))
{
	$error = 'Error adding submitted joke: ' . mysqli_error($link);
	include 'error.html.php';
	exit();
}

header('Location: .');
exit();
}

if (isset($_GET['deletejoke']))
{


$id = mysqli_real_escape_string($link, $_POST['id']);
$sql = "DELETE FROM joke WHERE id='$id'";
if (!mysqli_query($link, $sql))
{
	$error = 'Error deleting joke: ' . mysqli_error($link);
	include 'error.html.php';
	exit();
}

header('Location: .');
exit();
}

 

Many thanks :)

Link to comment
Share on other sites

Basically, include_once is used if you're not sure if you've already included a file or not.  Personally I try to stay away from it as I believe it tends to lead to lazy coding practices.  In regards to your code, the first way is technically more efficient in that it only includes the file if it is needed.  The second way you have (while less code) would always include the file whether you needed it or not.

Link to comment
Share on other sites

Ok I will explain with an example.

Example using include()

If I have the files functions.php, database.php and morefunctions.php

Database.php includes functions.php and morefunctions.php but functions.php already includes morefunctions.php so my php script will error out. I will get an error saying one of my functions has already been used (declared), Why? because essentially morefunctions.php has been called twice. This would not have happened if I had used include_once() as it does as it says on the tin and will not include files previously declared.

So If you know you are messy with your php code, then its safer to use the include_once(), but if you keep track of all your code, then its ok to use the include() function.

 

Link to comment
Share on other sites

Both require() and require_once() will result in a fatal error if the files are not found, and the same performance results match up with require() and require_once() as the are identical to include() and include_once() minus the fatal error.

 

Yup, which might be a good idea when you include a file that's absolutely crucial to your application and whose absence might have unpredictable results.

Link to comment
Share on other sites

True but it will also reveal your file structure, so maybe better to check for the existence of a function, class, variable, or constant that is in the included file. Then you can catch the lack of the file and take your own error handling actions.

Link to comment
Share on other sites

I'm having difficulty imagining a situation where the fact that a requested resource is inaccessible or nonexistent is not fatal to the further execution of the program. If I request a particular resource it's because I need it.

 

Just thinking the same.

 

If I'm inclusing a file it's because my script needs it. This is why I always use require or require_once(). I can't imagine what script you would try and include that you didn't actually need.

Link to comment
Share on other sites

I'm having difficulty imagining a situation where the fact that a requested resource is inaccessible or nonexistent is not fatal to the further execution of the program. If I request a particular resource it's because I need it.

 

Normally true, yes, but you may at times include files that are just plain text.

Link to comment
Share on other sites

So what? That doesn't change the fact that I need that resource (be it plain text, PHP code or something entirely different) for whatever reason. If I for some reason cannot access it or it doesn't even exist then I cannot do what I intended to do with it. If, however, script execution continues it would act as though it was successfully retrieved and that would result in unexpected behavior. In that case it would be better to halt script execution.

Link to comment
Share on other sites

So what? That doesn't change the fact that I need that resource (be it plain text, PHP code or something entirely different) for whatever reason. If I for some reason cannot access it or it doesn't even exist then I cannot do what I intended to do with it. If, however, script execution continues it would act as though it was successfully retrieved and that would result in unexpected behavior. In that case it would be better to halt script execution.

 

i agree 100%... its the difference between "i want"(include) and "i need"(require)... if you need a text/php/etc file, why then say that you want it? if you need it and its not there, it should automatically see and error accordingly... not just... ignore it and move on...

Link to comment
Share on other sites

Although I agree completly with you on the resource and having to have it. Would you still want to show that errror if you could avoid it? Just stating that it is still better to not present your users with a error page but rather to tell them that the resource was not found(with out revealing file structure) and then redirect them to a page that may give them something similiar. However this is highly unlikely that you would direct them to a non-existant resource.

Link to comment
Share on other sites

So what? That doesn't change the fact that I need that resource (be it plain text, PHP code or something entirely different) for whatever reason. If I for some reason cannot access it or it doesn't even exist then I cannot do what I intended to do with it. If, however, script execution continues it would act as though it was successfully retrieved and that would result in unexpected behavior. In that case it would be better to halt script execution.

 

Say you include a banner rotator at the top of your page and your layout is not affected by the absence of its display. Why use require here when the page will work just fine without the file? There are various other situations where include will be a good idea.

 

Overall I agree with you though, using require is generally better practice. Files that are to be used are normally there.  :P

Link to comment
Share on other sites

why would you require a file specifically for a rotating banner? its 2 lines of code lol

$f=glob('images/banners/*');
echo '<img src="'.$f[array_rand($f)].'">';

 

and you can always

if(file_exists()) require_once();
else echo 'error accordingly';

and then you have the file you need, and if it goes missing, you have the errors you want

Link to comment
Share on other sites

Although I agree completly with you on the resource and having to have it. Would you still want to show that errror if you could avoid it? Just stating that it is still better to not present your users with a error page but rather to tell them that the resource was not found(with out revealing file structure) and then redirect them to a page that may give them something similiar. However this is highly unlikely that you would direct them to a non-existant resource.

 

Then check if it exists and don't attempt to retrieve it if it doesn't.

 

why would you require a file specifically for a rotating banner? its 2 lines of code lol

$f=glob('images/banners/*');
echo '<img src="'.$f[array_rand($f)].'">';

 

and you can always

if(file_exists()) require_once();
else echo 'error accordingly';

and then you have the file you need, and if it goes missing, you have the errors you want

 

That sounds rather naive. What if I want to take into account that the banners should have a uniform distribution of impressions? What if I wanted to track clicks or impressions? What if...?

Link to comment
Share on other sites

why would you require a file specifically for a rotating banner? its 2 lines of code lol

$f=glob('images/banners/*');
echo '<img src="'.$f[array_rand($f)].'">';

 

and you can always

if(file_exists()) require_once();
else echo 'error accordingly';

and then you have the file you need, and if it goes missing, you have the errors you want

 

Banner rotation scripts are usually more complex than that  ;) That's kind of like echo "Hello world!". Eventually you want and need more.

Link to comment
Share on other sites

why would you require a file specifically for a rotating banner? its 2 lines of code lol

$f=glob('images/banners/*');
echo '<img src="'.$f[array_rand($f)].'">';

 

and you can always

if(file_exists()) require_once();
else echo 'error accordingly';

and then you have the file you need, and if it goes missing, you have the errors you want

 

Banner rotation scripts are usually more complex than that  ;) That's kind of like echo "Hello world!". Eventually you want and need more.

 

way off track here... lol

 

of course... and im just saying that banner rotation, to any extend is rarely more then 10-15 lines of code, you dont have to create a seperate file just for one simple function...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.