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:
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!
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)
Related
I'm trying to export some classes into a library to keep my code tidy
but I just don't know why this doesnt seem to work :(
the include file is definitely being loaded.
when I defined the class locally there was also no problem and testgerät was sent.
I always try to keep things simple at first so I'm using this small sample:
Gerät.php:
<?php
echo "loading Gerät<br>";
class Gerät{
function Gerät(){
$this->name = "testgerät";
}
}
?>
index.php
<?php
include "/var/www/html/aiberry/objects/Gerät.php";
echo "My first PHP script!<br>";
$test = new Gerät();
echo $test->name;
?>
the output of index.php
loading Ger�t
My first PHP script!
could this be a namespace issue?
EDIT: I'm sorry for causing confusion regarding the actual issue:
I am in fact expecting the output:
loading Ger�t
My first PHP script!
testgerät
If I knew how to turn the debugs on I would probably get a message telling me that there is no class "Gerät". The paradox for me though is that Gerät.php is definitely being loaded because the output "loading Gerät" is written within that file. a simple copy paste of the class into index.php delivers the desired output so i can only think of a name space issue or something alike where the class is just being lost after Gerät.php is done processing.
My guess is that you are having different charset encodings between the two files, can you verify with your text editor if Gerät.php was saved with the same character set encoding of index.php?
In general it's a good idea to avoid non-ascii character in PHP identifiers (class names, variable names, etc)
I am trying to include 2 php file in two separate <td> tags in the same table.
<td><?php include 'login.php';?> </td>
<td><?php include 'register.php';?> </td>
Both the php files include another php file for connecting to a database (eg. <?php include 'database.php';?>
Now, the problem is, the second file doesn't show up in the table. First file works.
Php files work independently. No problem with the code.
I removed the include in 1.php and everything worked fine - ie. both the files show up in table.
My conclusion is, it goes on including indefinitely. Now, how do I solve this?
regards
Ganesh Kumar
You can use include-once
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
i.e.:
include_once('database.php');
include_once('login.php');
include_once('register.php');
You actually have several options, now that I think about it.
Require_once:
require_once('database.php')
This is the most accepted method for files such as this one that you describe, as it will hard-fail if the file cannot be included. For files that do program instantiation (I.e. database connection) this method is preferred.
Include_once:
include_once('login.php')
I've never found a reason to use this statement over require_once; however, that said, it doesn't mean there isn't one. If you have a file that does some instantiation of something related to your programme that isn't mission-critical, then you could suppose to use this directive over the other.
Define Include Constants:
This method requires a bit more explanation: instead of starting your included file (database.php in our example) off with the code for it, start it off in a manner similar to C/C99/C++.
<?php
if (!defined("INCLUDED_DATABASE"))
{
define("INCLUDED_DATABASE", true);
// add main body of file here
}
?>
This method basically accomplishes the same thing as the include_once and require_once, except that in no circumstances will it ever actually process the body twice in one request, even if you forget to use _once as a suffice to your include/require method. This goes back to the old days of C/C99/C++
where including a file twice would hard-fail the compiler, as duplicate definitions would take place.
Personally, I have always preferred the last option: it's the most strict. Yes, require_once and include_once when used diligently will have the same effect, but suppose someone (not even you necessarily) is modifying the application and accidentally does an include or require without the _once suffix, they will be having a bad day. This method prevents that.
That said, I still use a require_once when necessary, and a require if it can be included multiple times. (Files with that designation are not designed with the define construct.)
Alright this is what my code looks like
index.php
require_once($WebsiteRoot . "/include/testfile.php");
TestFunction();
/include/testfile.php
function TestFunction()
{
echo "It Works";
}
And it gives me the error:
Fatal error:
Call to undefined function TestFunction() in /path/index.php on line 49
Any idea what i'm doing wrong?
Thanks
You haven't included a <?php tag in the included file, so it's just interpreted as plaintext input.
Remember... there's no such thing as a PHP script. There's only files which contain PHP code blocks. Without at least one <?php opening tag, the PHP interpreter will never be invoked and the file's contents will simply be treated as output.
try calling another function from testfile.php, if this is'nt working, its something with the include. Add the code:
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
to the top of index.php and refresh the browser to see your errors, try debugging from there.
The problem that i can forsee is that you are using a URL instead of a path, your $websiteRoot variable should contain a path like:
$websiteRoot = "/var/www/html/websiteName";
OR
$websiteRoot = "C://xampp/htdocs/websiteName";
instead of a URL like:
$websiteRoot = "http://www.somesite.com";
I had a similar issue. I dug into the PHP in the included file and found an invalid PHP tag. I had <? instead of <?php. PHP 7.2 and earlier forgave that, but PHP 7.3 was throwing that same error you faced.
Make sure you're including the file you think you are. If your index.php page looks exactly like you've stated, then it won't return anything.
If you want to link to the same location from anywhere on the site without worrying about relative locations, then at the beginning of the file, put:
$WebsiteRoot=$_SERVER['DOCUMENT_ROOT'];
And it should work fine, provided your file would be located at http://mywebsite.com/include/testfile.php
Try renaming the included file.
I had an included file with the name "system.php". It looked as if the include command was just skipped. Even with the most strict error reporting there was no message and even an echo command in the main body of the included file did not produce output. It had worked ok under PHP 5 but after the upgrade to a 7.2 environment these problems arose. After much effort - I forgot how - I managed to get an error message. It said there was a conflict with a PEAR class with the name "system". Yet my file didn't contain any class, just variables and functions. Anyway, giving the file another name than "system.php" worked for me.
I hope someone else can add a more technical comment on what was going wrong here.
From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.
How can include a external class in a php file?
example:
//Test.class.php
<?php
class Test{
function print($param){
echo $param;
}
}
?>
//######################################################
//test.php
<?php
include('http://www.test.com/Test.class.php');
$obj = new Test();
echo $obj->print("hola");
?>
The class is on another server. I have enabled the allow_url_include and allow_url_fopen.
Why can't I call the function print?
The remote file must output the php source code, not execute it.
To output the PHP code instead of executing you could simply remove the .php extension from the file.
PS: Are you really, really, really sure you need remote inclusion? It's a BIG security risk!
What you're including from the other server isn't the code behind the PHP but the output from it (if you visit that page in a browser you aren't seeing the PHP code if you view source right?)
You either need to reconfigure the other server not to execute the code but display it (not a good idea if it's in any way shared or needs to execute it's own code), or rename the other file to something that isn't first interpretted (try otherfile.php.txt)
Have a look at the documentation:
(...) If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.
Probably the server, you are trying to get the file from, executes the PHP file and only the result (which is empty) is included. You would have to configure the server in such a way that it outputs the PHP code. But this is not a good idea if it is sensible code.