PHP helper function for path

Updated: 17th July 2024
Tags: php

If you don't use any framework consider creating simple config.php file with

//config.php
//place in root of your directory
<?php
define('APP_ROOT', dirname(__FILE__));
<?php
//app/helpers.php
function getFullPath(?string $relativePath = null): string
{
    if (!$relativePath) {
        return APP_ROOT;
    }
    $relativePath = ltrim($relativePath, '/');
    return APP_ROOT . "/$relativePath";
}

function storage_path(?string $relativePath = null): string
{
    if (!$relativePath) {
        return APP_ROOT .  "/storage";
    }
    $relativePath = ltrim($relativePath, '/');
    return APP_ROOT . "/storage/$relativePath";
}

function public_path(?string $relativePath = null): string
{
    if (!$relativePath) {
        return APP_ROOT . "/public";
    }
    $relativePath = ltrim($relativePath, '/');
    return APP_ROOT . "/public/$relativePath";
}

So if you use composer add autoload files like helpers and config.php

{
    "require": {
       
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": ["app/helpers.php", "config.php"]
    }
}

If you don't use composer you will need to require config.php and app/helpers.php. This way you can use helpers in php function and forget about path problems once and for all.

Feel free to modify (you can mege everything in config.php and rename it to path_helpers.php, etc)