phpincluderelative-path

Including a class using a relative path


I'm trying to use a library in one of my classes, namely the PHPass library.

This is my basic directory structure:

/ (root)
    / mysite
        /application
            /models
                User_model.php
            /libraries
                PasswordHash.php

I want to include PasswordHash.php in User_model.php. I tried doing this:

// Load PHPass library
include_once('..\libraries\PasswordHash.php');
$hasher = new PasswordHash(8, TRUE);

But PHP can't find the file:

Message: include_once(..\libraries\PasswordHash.php) [function.include-once]: failed to open stream: No such file or directory

Solution

  • It depends on your current working directory, not the script it actually parses now. Try dumping

    getcwd() 
    

    function output to figure out the current working dir. In order to use current file path, you can try

    realpath(__FILE__) 
    

    and then construct relative path to it. Also, in order to not confuse slashes, you may use DIRECTORY_SEPARATOR constant to separate folders, like:

    require_once(realpath(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'class.php')