Search code examples
phppathrequire-once

understanding relative paths and absolute paths


Wondering why php keeps telling me a file doesnt exist when it does.

this is my code and error

    require_once('/book/admin/bin/class/db.class.php');

Error and stack trace

   Warning: require_once(/book/admin/bin/class/db.class.php) [function.require-once]: failed to open stream: No such file or directory in C:\wamp\www\book\forms\add.php on line 3
    Call Stack
    #   Time    Memory  Function    Location
    1   0.1479  408440  {main}( )   ..\add.php:0

This happens a lot and i want to rectify this annoying reoccurring problem. Is there a way I can set up my web server to read from the root of the site like I'm asking it too? Or am I misunderstanding what is happening.

This is how directory structure looks.

using a wamp server

c:\wamp\www\book <- my site root
c:\wamp\www\book\forms <- where add.php is located
c:\wamp\www\book\admin\bin\class\db.class.php

Why can I not use filepath as "/book/bin/"

Thanks, C


Solution

  • Absolute paths on Windows starts with a drive letter. You can use

    require_once 'c:\wamp\www\book\admin\bin\class\db.class.php';
    

    or you can use a relative path.

    To see what path you "start out" at use getcwd(); This is probably the directory where the script "starts", e.g. the directory where index.php is located.

    echo getcwd();
    

    You can require files relative to this dir.

    However, I suggest you set a define a constant called APPLICATION_DIR or something like that and build links from that.

    define('APPLICATION_DIR', 'c:\wamp\www\book');
    require_once APPLICATION_DIR.'\admin\bin\class\db.class.php';