Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Basename in PHP | PHP basename() Function

Updated on 03 July, 2023

6.27K+ views
8 min read

Introduction

PHP has a function called basename that helps to fetch the filename present at the specified path. The function returns and prints the filename or the directory path passed in arguments. The procedure also displays the script name if the basename used is $0. Programmers use this function to check the files present at the specified location or use the program flow filenames.

Hence, the programmers use the basename function in PHPto find the files present at any location and get them printed on the console. The basename function is like any other built-in function or user-defined function in PHP, such as string functions, math functions, numeric functions, date functions, and many more.

Check out our free courses to get an edge over the competition. 

Basename Function in PHP

The basename is an in-built function in PHP, which returns the file name present at the path provided as an argument.

Syntax:

Below is the syntax to use the Basename function in PHP.

String basename($path, $suffix)

The function has two parameters, i.e., path and suffix.

  • $path: Path is a mandatory parameter and s of String type. This parameter specifies the path at which the file is to locate.
  • $suffix: Suffix is an optional parameter that hides the file extension if the file has a suffix.

Check out upGrad’s Advanced Certification in DevOps 

The function returns the file basename, which is present at the path passed as $path in the basename parameter.

Examples of Basename in PHP

Example1: The code prints the name of the file present at a specified location without using the optional parameter $suffix.

<?php

// Save the path in the $path variable

$path = “/ExampleProject1/Example1.php”;

// basename function finds the name of the file present at $path and saves it in //$fileName variable

$fileName = basename($path);

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

// Prints the filename

Echo $fileName;

Echo “\n”

?>

Output:

Example1.php

Here, only the $path parameter is passed with the basename function call, so the complete file name gets printed.

Example2: The code prints the file’s name at the specified location when the optional parameter $suffix is passed.

<?php

// Save the path in the $path variable

$path = “/ExampleProject1/Example1.php”;

// Using the $suffix parameter so that the output contains only the filename, without //extension

$fileName = basename($path, “.php”);

Echo $fileName;

?>

Output:

Example1

Here, $suffix is passed with a function call, so only the file name gets printed without extension.

Example3: The code prints the name of the file present at the specified location with both versions of the basename function.

<?php

// Save the path in the $path variable

$path = “/Project1/team1/FirstProgram.php”;

// Using the $path parameter with basename function

$fileName = basename($path);

Echo $fileName;

Echo “\n” // It takes the cursor to next line

// Using the $path parameter with basename function

$fileName = basename($path, “.php”);

Echo $fileName;

?>

Output:

FirstProgram.php

FirstProgram

When only the $path is passed as a parameter, the complete filename gets printed. When the $suffix .php is passed with a function call, the .php gets hidden and only filename gets printed.

Errors and Exception in Basename in PHP

It is indeed necessary to understand the functioning and usage of basename function in PHP, but it is also crucial to understand the exceptions to use the process accurately:

Basename function in PHP

Cannot identify the $path value given as ‘..’; however, it can recognise the single dot ‘.’. Double beads ‘..’ are only used in Linux that move the location from the current directory to the previous directory. As double dots ‘..’ is used in Linux only, sobasename in PHP only recognises the single drop ‘.’.

Basename function in PHP

Uses the $path passed as string and is not aware of the file system. It implies that the process only works on the way passed as a parameter irrespective of the filesystem type. The file system can be Mac, Linux, and Windows. As each of these file systems has a different format, and basename function cannot recognise the type of filesystem used. Therefore, the output can get wrong. Hence, it is recommended to pass parameters in the basename function.

Slashes are used as the separator in the directory path or to separate the folders. Windows platform can recognise both backslash (\) and forward-slash (/) as a separator in the directory path, while in other environments, only forward-slash (/) gets used. So, we should use slash cautiously while using the basename function in PHP.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Handling Errors and Exceptions

When using the basename( ) function in PHP, it’s crucial to be aware of potential errors and exceptions. One common error occurs when an invalid file path is provided. This can lead to unexpected outcomes, such as an empty base name or incorrect results. To avoid such issues, it is essential to ensure that the file path is accurate and accessible.

By validating the file path and handling any potential errors or exceptions, you can maintain the reliability and integrity of your PHP code.

Syntax

The syntax of the basename in PHP file is straightforward and follows this structure:

basename(path, suffix)

In this syntax:

path: Represents the file path as a string.

suffix (optional): Denotes the suffix to be removed from the base name. It is also provided as a string.

By adhering to this syntax, you can effectively utilize the basename( ) function in your PHP code.

Understanding the Return Value

The basename( ) function in PHP returns the base name of the file, excluding the directory path. This extracted base name is useful when you need to isolate and work with the file name separately from the entire path.

The return value of the basename( ) function is a string, representing the base name of the file. This value can be assigned to a variable or directly utilized in your PHP program to perform further operations or display information to the user.

Example:

<?php

$path = “/var/www/html/index.php”;

$basename = basename($path, “.php”);

echo $basename;

?>

Live Demo:

https://www.example.com/  

Output:

index
In this example, the basename function removes the directory path and the suffix “.php” from the given file path.

Basename PHP in Javascript

In JavaScript, there is no built-in function like basename PHP. However, one can implement a similar function using JavaScript code. The basename PHP function returns the filename component of a path, removing any directories or slashes. The following example shows how you can achieve the same using JavaScript:

function basename(path) {

  // Normalize the path by replacing backslashes with forward slashes

  path = path.replace(/\\/g, ‘/’);

  // Get the last part of the path after the last slash

  var lastIndex = path.lastIndexOf(‘/’);

  var filename = path.substr(lastIndex + 1);

  // Return the filename

  return filename;

}

// Example usage

var fullPath = ‘/path/to/somefile.txt’;

var filename = basename(fullPath);

console.log(filename); //

Output: 

somefile.txt

Conclusion

This was all about the basename function in PHP. We hope you have a deep understanding of PHP’s basename, usage, syntax, and different exceptions. The exceptions should be considered before using the basename function so that the correct output can be expected from it.

If you’re interested to learn more about full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development, which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What is a basename() function in PHP?

In PHP, basename is the name of the last directory in the path to a file, meaning the portion of the path that comes after the last slash. The basename() function returns a file name component, without any path information. Basename() function is used in PHP programming language. This is useful in cases when you work with reading or writing data into files in PHP. There might be cases where you want to read from a file in the same directory where your current file is. Also, if you want to specify the name of a file based on the name of the directory, you can extract the folder name using the basename() function and rename the file accordingly.

2. How to work with files in PHP?

The file functions of PHP help you to work with the files, keeping in view the safety, security, and ease. The PHP file functions, when used in combination with FTP functions, can be used for reading, writing and uploading and downloading the files from the server through the Internet. The basic syntax of the PHP file functions is $_FILES. These functions are used to access the uploaded files.

3. How to become a PHP developer?

There are two ways to become a PHP developer. One is the formal way and the other is self-learning. If you want to become a PHP developer by passing a certification exam, then you need to go to a good college and earn a degree in computer science. Once you are done, you can find a job and start learning PHP on the job. The disadvantage of the above method is that you would have to wait for the job to give you an opportunity to start learning. Another disadvantage is that you could get stuck with a salary job and may not have enough time to learn PHP. If you want to become a PHP developer by self-learning, then you need to spend time on the Internet to find resources. After that, you need to allocate some time every day to learn PHP. It all depends on you, but I think the self-learning way is better than the formal way.

RELATED PROGRAMS