How to work with filesystem paths in PHP

PHP offers you several utilities to help you work with paths.

You can get the full path of the current file using any of:

  • __FILE__, a magic constant
  • $_SERVER['SCRIPT_FILENAME'] (more on $_SERVER later!)

You can get the full path of the folder where the current file is in using:

  • the getcwd() built-in function
  • __DIR__, another magic constant
  • combine __FILE__ with dirname() to get the current folder full path: dirname(__FILE__)
  • use $_SERVER['DOCUMENT_ROOT']

Download my free PHP Handbook!