How to get current directory, filename and code line number in PHP

PHP provides large number of magical constants. These all constants are case sensitive. With the help of these constants, we can get current directory, filename, current line number and much more.

How to get current directory, filename and code line number in PHP

These are the some examples of PHP Magic Constants.


To get the current directory

__DIR__ : This constant is used to get the current directory of the file. This is equivalent to the dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. If used inside an include method, the directory of the included file is returned.

<?php echo "The current directory of this file is '" . __DIR__ . "'.\n"; ?>

Output: The current directory of this file is 'C:\wamp\www\demo'.


To get the current filename with full file path

__FILE__ : This is used to return the full file path and filename of the file. If used inside an include method , the name of the included file is returned.

<?php echo "The current file with path is '" .  __FILE__ . "'.\n"; ?>

Output: The current file with path is 'C:\wamp\www\demo\magic_const.php'.
This magic constant is mostly used in case where we have to include some files from the directory.



To get the current line number

__LINE__ : This is used to return the current line number of the file.

<?php echo "The line number of this code is '" .  __LINE__ . "'.\n"; ?>

Output: The line number of this code is '34'.
This constant is mostly used while debugging the code, or to get line number of the error.





Related Articles

Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
CRUD operations in Python using MYSQL Connector
Windows commands to Create and Run first Django app
How to send emojis in email subject and body using PHP
PHP7.3 New Features, Functions and Deprecated Functions
Create pie chart using google api






Read more articles


General Knowledge



Learn Popular Language