File Directory Constants

suggest change

Current file

You can get the name of the current PHP file (with the absolute path) using the __FILE__ magic constant. This is most often used as a logging/debugging technique.

echo "We are in the file:" , __FILE__ , "\n";

Current directory

To get the absolute path to the directory where the current file is located use the __DIR__ magic constant.

echo "Our script is located in the:" , __DIR__ , "\n";

To get the absolute path to the directory where the current file is located, use dirname(__FILE__).

echo "Our script is located in the:" , dirname(__FILE__) , "\n";

Getting current directory is often used by PHP frameworks to set a base directory:

// index.php of the framework

define(BASEDIR, __DIR__); // using magic constant to define normal constant

—``` // somefile.php looks for views:

$view = ‘page’; $viewFile = BASEDIR . ‘/views/’ . $view;

# Separators

> Windows system perfectly understands the `/` in paths so the
> `DIRECTORY_SEPARATOR` is used mainly when parsing paths.

Besides magic constants PHP also adds some fixed constants for working with paths:

* `DIRECTORY_SEPARATOR` constant for separating directories in a path. Takes value  `/` on \*nix, and `\\` on Windows.
The example with views can be rewritten with:

$view = ‘page’; $viewFile = BASEDIR . DIRECTORY_SEPARATOR .’views’ . DIRECTORY_SEPARATOR . $view; ```

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Magic constants:
* File Directory Constants

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
28 Magic constants
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR