Hi friends, sometimes we are facing such a situation where we have to get the current page name from the URL. Then based on the current page name we performed specific tasks for that page only. So, in this tutorial, I will show you how to get the current page name using PHP. It is very simple and one or two line of code.
Also, you may be interested to read the following tutorials —
- How to get current page URL using PHP
- Populate multiple dropdown lists using Ajax, jQuery, PHP, and MySQL
- A simple way to generate a random password using PHP
- How to get data from database in JSON format using Ajax and PHP
- How to insert JSON data into MySQL database using PHP
- How to generate QR code using PHP and Ajax
- How to generate barcode using PHP
- Like dislike rating system using jQuery, Ajax, PHP and MySQL
- Load data dynamically on page scrolling using jQuery, Ajax, PHP, and MySQL
- Ajax login form using jQuery, PHP, PDO, MySQL and Bootstrap
- Bootstrap pagination in PHP and MySQL
- How to reduce or compress image size while uploading using PHP
- Store and retrieve image from database using PHP and MySQL
- Login with Facebook using PHP and MySQL
Get the current page name without extension using PHP
$info = pathinfo( __FILE__ ); $page = $info['filename']; //output : index
The pathinfo() function returns an array that contains the information about a path. filename key holds the file name without extension so it will return the page name only.
$page = pathinfo(__FILE__, PATHINFO_FILENAME); //output : index
Also, the above line of code returns the current page name without extension. But, I will recommend you to use $_SERVER[‘PHP_SELF’] instead of __FILE__. Because if the code ran from another file then it would break.
$page = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); // output : index
Get the current page name with extension using PHP
$page = basename($_SERVER['PHP_SELF']); // output : index.php
The above PHP code returns the current page name with extension.
If you face any problem feel free to inform me in the comment section below. Please like and share this tutorial how to get the current page name using PHP with others. Kindly subscribe Mitrajit’s Tech Blog to keep yourself updated with the upcoming tutorials.