0

In my web page, I wrote:

<?php
//define('__PUBLIC__', $_SERVER['DOCUMENT_ROOT'].'/public'); 
$doc_public = $_SERVER['DOCUMENT_ROOT'].'/public';
echo "Before include...<==============>$doc_public";
?>
<?php require_once($doc_public.'/inc/head.php');  ?>
<?php echo "After include...<==============>$doc_public"; ?>

And the page shows: enter image description here

This firstly happened when I notice the fatal error in the footer, but the head is fine.

Although I can implement define or constant variable to avoid this, I am still curious how it happens.

P.S.: I run this under Apache with a port 8001. This is set in 【apache\conf\extra\httpd-vhosts.conf】. I am running more than one webapp under this site. I just share this information, as I am not sure this has anything to do with this case.

Thanks!

4
  • 1
    Are you sure it's not being modified in head.php? Commented Nov 19, 2018 at 3:24
  • FYI, __DIR__ is much more reliable than $_SERVER['DOCUMENT_ROOT'] for creating paths to your scripts Commented Nov 19, 2018 at 3:27
  • 1
    For all intents and purposes, using an include file is the equivalent of copy pasting the code from the file into the script, at the position it is placed. Commented Nov 19, 2018 at 3:29
  • So what's the problem here? Is it that your $doc_public variable appears to change - loosing the slash before public? If so, look for any references/code that modifies $doc_public. Commented Nov 19, 2018 at 3:42

1 Answer 1

2

When you require a file, if a variable is modified it affects the original script as well, that's how it's designed. Require doesn't create a secondary environment separated from the including file, it just adds the PHP code in sequence, exactly like if you had written the code in the initial file.

Have a look at the official PHP documentation, the first example is exactly the same as your case

http://php.net/manual/en/function.include.php

(include is the same as require, the latter just throws an error. For more info about differences between include and require http://php.net/manual/en/function.require.php)

Sign up to request clarification or add additional context in comments.

1 Comment

"Require doesn't create a secondary environment separated from the including file" 👈 true, but namespace does 🙂

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.