Reputation:
I have a curiosity. What happens if a PHP script includes itself?
The reason I ask is that I have a php file that generates the contents for all of my site's <head>
tags. That includes the site's 404 error page
head
tag.
If the php file that generates these head
tags is accessed directly it "pretends" to not exist by including the 404 error page
, which sends 404 status
back to the client.
This is what the filesystem looks like:
/
.htaccess <- (apache 404 handling)
404.php <- 404 error page
head.php <- '<head>' generator
...
404.php
contains:
<?php
header("HTTP/1.0 404 Not Found");
?>
<html>
<head>
<?php
$key = true;
include dirname(__FILE__) . "/head.php";
?>
</head>
<body>
lul. dead.
</body>
</html>
head.php
contains:
<?php
if(isset($key) && $key===true){
//code to generate <head> content
}else{
include dirname(__FILE__) . "/404.php";
}
?>
$key
tells head.php
that it was included by another php file and not requested over URL.
So, to sum up, if I directly request head.php
from my web browser (not accessing it via php includes
, just via http request) it should:
(a) realize that the request was not an include
from another php file, then
(b) include 404.php
, which
(c) sends a 404 status
on line 2
of 404.php
and, then,
(d) includes head.php
.
Therefore, eventually head.php
will include head.php
.
does this happen?
Upvotes: 0
Views: 529
Reputation:
Yes, it does.
NOTE: However, an internal server error can occur. For example:
include.php
:
<?php
if(!isset($s)){
$s = 0;
}
if($s<10){
include "include.php";
$s++;
}
?>
test
This script produces an internal server error. I did not check to see how many times a file can be self-included before the error occurs, but apparently 10 times is (or is more than) enough times to cause the error.
Either that or a PHP script can not directly include itself. It has to do so through including a separate script which includes the original script
Upvotes: 1