How to get current directory, filename and code line number in PHP
PHP provides a large number of magical constants. All these constants are case sensitive. With the help of these constants, we can get the current directory, filename, current line number and much more. It is more secure, reliable, and fast, which has resulted in web developers preferring to work with PHP. So, it does not matter if the developer needs to know the line number or current directory of the PHP document.
These are 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 ArticlesPHP reverse a string without predefined function
PHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
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
To Sort MySQL Table Data In PHP
To check whether a year is a leap year or not in php