Need help with <?php include

Discussion in 'PHP' started by Ajeet, Aug 11, 2011.

  1. #1
    I want to include a file using something like:

    <?php include 'header.txt'; ?>

    The problem is that my header.txt is in the root directory, and I am placing this code in various directories and sub directories. How do I state the path such that the same header.txt is always included?
     
    Solved! View solution.
    Ajeet, Aug 11, 2011 IP
  2. #2
    You will need to get the full php path to the specific file from the server root. If you have shell access you should be able to just go into the directory with the header.txt file and type "pwd" to get the current path, but if not then make a php file in the same directory as the header.txt file. Put this in the contents:
    <?php
    echo __DIR__;
    ?>
    PHP:
    Navigate to that page in the browser to get the path to the current directory with symlinks resolved. Copy that string (we'll call it $dir). Now to include that text file anywhere, use this code:
    
    include $dir.'/header.txt';
    
    PHP:
     
    Thorlax402, Aug 11, 2011 IP
  3. insert

    insert Peon

    Messages:
    148
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Just use absolute path to the script...
     
    insert, Aug 11, 2011 IP
  4. Ajeet

    Ajeet Well-Known Member

    Messages:
    2,511
    Likes Received:
    503
    Best Answers:
    0
    Trophy Points:
    185
    #4
    Am I doing something wrong. Upon following your instructions, all I get is
    __DIR__;
    on the screen.

     
    Ajeet, Aug 11, 2011 IP
  5. insert

    insert Peon

    Messages:
    148
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    __DIR__ constant was added in PHP 5.3.0, maybe you're using older version of PHP. In older versions, the same behaviour will be achieved by dirname(__FILE__). But I don't think this solves your problem. __DIR__points to the directory where your PHP script is, not to the root. As I said, use absolute (full) path to the header.txt file and it will work...
     
    insert, Aug 11, 2011 IP
  6. ZeroGamma

    ZeroGamma Peon

    Messages:
    35
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Try echoing $_SERVER['DOCUMENT_ROOT'], this will output the path to the document root of your web hosting account. You can then use this variable along with the 'header.txt' text to get a full, absolute path to use for the include or require statement.
     
    ZeroGamma, Aug 12, 2011 IP
  7. insert

    insert Peon

    Messages:
    148
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    But if you use $_SERVER['DOCUMENT_ROOT'], then the header.txt file msut be visible "from the outside"...
     
    insert, Aug 12, 2011 IP