Mastering PHP File Paths: Simplifying Your Project’s Structure

Have you ever tried including a file in your project and needed clarification about how to go about it? You usually start with a simple folder structure that can quickly escalate to a complex folder structure. This article will discuss the absolute and relative paths, directory separators, file functions, including files in PHP, and how to use file paths in PHP.

All paths will be in Windows OS format. An example will be like this;

$file = 'C:/xampp/htdocs/project/includes/config.php';
Enter fullscreen mode
Exit fullscreen mode

In this article, we take a more practical approach to explain the file paths in PHP. Let’s assume that we have a project structure as below.

tutorials/ |-- database/ |-- |-- connection.php
|-- report/
|-- |-- admin/approvals.php
|-- |-- tracker.php
|-- signin.php
Enter fullscreen mode
Exit fullscreen mode

Absolute vs. Relative File Paths

To add a file to your project, you need to know the location or path of the file. Knowing the file location, you can decide to add the file in two ways; absolute or relative file path.

Absolute Path

An absolute file path specifies the complete and precise location of a file or directory in the filesystem. It starts from the root directory and includes directories up to the target file or directory. It does depend on the current working directory (CWD) and it points to the same directory regardless of the script is run.

Using the absolute path, we can include the connection.php file in the project1 directory like this;

// tutorials/signin.php
$path = "c:/xampp/htdocs/tutorials/database/connection.php"; // absolute path to database/connection.php // tutorials/report/tracker.php
$path = "c:/xampp/htdocs/tutorials/database/connection.php"; // absolute path to database/connection.php // tutorials/report/admin/approvals.php
$path = "c:/xampp/htdocs/tutorials/database/connection.php"; // absolute path to database/connection.php
Enter fullscreen mode
Exit fullscreen mode

This path assumes that the parent directory, ‘tutorials’, is at c:\xampp\htdocs.

Relative Path

The relative path does not start from the root directory. It depends on or relative to the current working directory or any other directory.

When the file is inside the current working directory, use one dot sign ‘.’, and two dots ‘..’ when the file is relative to the parent directory or other directories relative to the file.

Let’s get the ‘tutorials/database/connection.php’ file path relative to the other directories;

// tutorials/signin.php
$path = "./database/connection.php"; // (./) relative to the current tutorials directory // tutorials/report/tracker.php
$path = "../database/connection.php"; // (../) moves one level up to the tutorials directory // tutorials/report/admin/approvals.php
$path = "../../database/connection.php"; // (../../) moves two levels up to the tutorials directory
Enter fullscreen mode
Exit fullscreen mode

Directory Separators in PHP

When you look closely at our paths, you realize we use forward slashes, (‘/’). The forward  (‘/’) and the backslash  (‘\’) slashes, called directory separators are used to separate directories in a file system.

The forward slash simplifies path handling and enhances cross-platform compatibility on Unix-like systems and is supported on Windows.

The backslash is used mostly on Windows systems. The double backslash functions as an escape character string.

PHP File Path Functions

PHP has many built-in functions that can be used to manipulate file paths. These functions help in constructing, analyzing, and managing paths in a platform-independent manner. Some key functions include;

  • basename(): This returns the filename component of a path. It takes two parameters, a path that specifies the path of the file, and a suffix that is used to specify the suffix to remove from the end of the returned file.
$filename = basename($path); // connection.php
$filenameWithoutExtension = basename($path, '.php'); // connection
Enter fullscreen mode
Exit fullscreen mode


dirname(): This returns the directory name component of a path. It takes the $path parameter and optional $levels which specifies the directory levels.

$path = "htdocs/tutorials/database/connection.php"; $directory = dirname($path); // htdocs/tutorials/database
$directorySecondLevel = dirname($path, 2); // htdocs/tutorials
Enter fullscreen mode
Exit fullscreen mode


realpath(): It is used to convert relative path to absolute path.

$relativePath = "../database/connection.php";
$absolutePath = realpath($path); // C:\xampp\htdocs\tutorials\database\connection.php
Enter fullscreen mode
Exit fullscreen mode


glob(): This method finds pathnames matching a pattern. It returns an array of PHP files in the specified directory.

$path = "tutorials/report/*.php";
$files = glob($path); // $files will contain an array of PHP files in the specified directory
Enter fullscreen mode
Exit fullscreen mode


file_exists(): This method checks whether a file or directory exists. It returns a boolean value.

$path = "../database/connection.php";
$files = file_exists($path); // $files will contain an array of PHP files in the specified directory
Enter fullscreen mode
Exit fullscreen mode

Including Files in PHP

For code organization, reusability, and maintaining modularity in PHP applications, you can use the include() and require() functions to add and evaluate files while executing a script.

The include() function will generate a warning if the file cannot be found, but the script will continue to execute.

The require() function will generate a fatal error if the file cannot be found, and the script will stop running.

To use these functions, you need to specify the file path correctly. You can either use absolute paths or relative paths depending on your needs. The file must be in the correct location and must have the correct name (case-sensitive).

Conclusion

As a software developer using PHP, it is very important to understand file paths. You must also know when to include files using either the include() or require() functions to help with code organization, reusability, and modularity.

Use absolute paths when possible but can be inflexible if the scripts need to be moved to a different server or directory.

Use the dirname() function to get the directory of the current file which can help to build relative paths. Relative paths can be ambiguous if the script is used in different contexts.

Check the existence of a file using file_exists() functions before including it because an incorrect path can lead to errors and security vulnerabilities.

Thank you for reading. See you on the next one.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top