PHP

INCLUDE FILE PATH IN PHP - RELATIVE VS ABSOLUTE

ABSOLUTE - FULL PATH include "D:\http\lib\SCRIPT.PHP"; RELATIVE - BASED ON CURRENT WORKING DIRECTORY (CWD) include "lib\SCRIPT.PHP";

RELATIVE & ABSOLUTE PATH

01

CWD IS THE FOLDER OF THE SCRIPT. IF WE RUN DEMO.PHP: echo getcwd(); D:\HTTP\

WHAT IS CWD? (A)

02

WE HAVE A TEST SCRIPT AT D:\HTTP\DEMO.PHP

WHAT IS CWD? (B)

03

RELATIVE PATH IS BASED ON CWD. IF WE INCLUDE FILES IN DEMO.PHP include "SCRIPT.PHP"; include "LIB\SCRIPT.PHP"; 

THE ABOVE WILL RESOLVE TO D:\HTTP\SCRIPT.PHP D:\HTTP\LIB\SCRIPT.PHP

SCRIPT 1 - D:\HTTP\A.PHP include "lib/B.PHP"; SCRIPT 2 - D:\HTTP\LIB\B.PHP echo getcwd();

RELATIVE PATH CONFUSION

04

CWD IS FIXED TO THE FIRST SCRIPT. IF WE ACCESS A.PHP DIRECTLY WORKING DIRECTORY - D:\HTTP\ BUT IF WE ACCESS B.PHP DIRECTLY WORKING DIRECTORY - D:\HTTP\LIB\

SCRIPT 1 - D:\HTTP\A.PHP include "lib/B.PHP"; SCRIPT 2 - D:\HTTP\LIB\B.PHP echo __DIR__;

DIR MAGIC CONSTANT

05

TO GET FOLDER OF "CURRENT SCRIPT", USE __DIR__ INSTEAD

ACCESSING A.PHP OR B.PHP WILL NOW SHOW "D:\HTTP\LIB\".