Make Path Relative in Symfony 7

Make Path Relative in Symfony 7

In Symfony, the Filesystem component provides a powerful set of tools to interact with the file system. When dealing with file paths in the application, it's crucial to maintain flexibility and adaptability. One common requirement is to make paths relative, ensuring seamless transitions between different environments or directory structures. This tutorial shows how to make path relative in Symfony 7.

Path class

The makeRelative method of the Path class is designed to simplify the process of transforming absolute paths into relative ones. This method accepts two absolute paths and returns the relative path from the second path to the first one.

<?php

require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\Filesystem\Path;

$first = '/var/www/project/public/images';
$second = '/var/www/project';
echo Path::makeRelative($first, $second); // public/images

The following table presents various cases to better to understand of how the method operates:

First argumentSecond argument (Base)Result
/var/www/project/public/images/var/www/projectpublic/images
/var/www/project/public/images/var/www/project/publicimages
/var/www/project/public/var/www/project/public/images..
/var/www/project/var/www/project/public/images../..
/var/www/project/public/var/www/project/public(Empty string)
/etc/php/var/www/project/public../../../../etc/php
/var/www/project/public/etc/php../../var/www/project/public
var/www/project/public/var/www/projectvar/www/project/public
/var/www/project/publicvar/www/projectException

Filesystem class

Symfony also supplies the makePathRelative method within the Filesystem class, designed to convert absolute paths to relative ones. However, it's important to note that this method appends a trailing / to the output and raises an exception if the first argument does not represent an absolute path.

<?php

require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\Filesystem\Filesystem;

$filesystem = new Filesystem();

$first = '/var/www/project/public/images';
$second = '/var/www/project';
echo $filesystem->makePathRelative($first, $second); // public/images/

Here's a table to help you grasp how the method works and compare it to the previous one:

First argumentSecond argument (Base)Result
/var/www/project/public/images/var/www/projectpublic/images/
/var/www/project/public/images/var/www/project/publicimages/
/var/www/project/public/var/www/project/public/images../
/var/www/project/var/www/project/public/images../../
/var/www/project/public/var/www/project/public./
/etc/php/var/www/project/public../../../../etc/php/
/var/www/project/public/etc/php../../var/www/project/public/
var/www/project/public/var/www/projectException
/var/www/project/publicvar/www/projectException

Leave a Comment

Cancel reply

Your email address will not be published.