include_once, relative path in php

Matrix001 picture Matrix001 · Oct 20, 2011 · Viewed 27.3k times · Source

I have 3 files: home, failed_attempt, login.

The file home and failed_attempt all refer to login file.

The annoying thing is that they throw a mistake saying that the login file doesnt exist. home will throw an exception if i do this, but failed_attempt wont.

  include_once("../StoredProcedure/connect.php");

include_once("../untitled/sanitize_string.php");

and if I do this:

   include_once("StoredProcedure/connect.php");
   include_once("untitled/sanitize_string.php");

the opposite happens, failed_attempt throws an exception , but home, wont. How do I fix this..

Do I tell the include to go up a page by putting this ../ , and therefore home.php doesnt need to go one page up therefore it throws that exception..

How can I make it so both files accept those inclueds as valid.. perhaps not relative to where they are placed.. i.e. without that ../

Directory structure:

PoliticalForum
->home.php
->StoredProcedure/connect.php
->untitled/sanitize_string.php
->And other irrelevant files

Answer

CD001 picture CD001 · Oct 20, 2011

Things like realpath() and __DIR__ are your friends when it comes to creating paths in PHP.

Realpath http://php.net/manual/en/function.realpath.php

Magic constants http://php.net/manual/en/language.constants.predefined.php

Since include and require are language constructs (rather than functions) they don't need brackets. Generally speaking you'd use include to include "templates" (output files) and require to include PHP files such as classes.

So you could use something like:

$sPath = realpath( __DIR__ . '/../relative/path/here');
if($sPath) { require_once $sPath; }

(use dirname(__FILE__) instead of __DIR__ on PHP < 5)

It's worth evaluating the path before attempting to require the file as realpath() returns false if the file doesn't exist and attempting to require false; spaffs out a PHP error.

Alternatively you can just use absolute paths like:

require /home/www/mysite.com/htdocs/inc/somefile.php