File Paths in PHP

Here’s the translation of the Go code to PHP, with explanations in Markdown format suitable for Hugo:

The dirname() and basename() functions in PHP provide functionality to parse and construct file paths in a way that is portable between operating systems.

<?php

// Join should be used to construct paths in a portable way.
// It takes any number of arguments and constructs a hierarchical path from them.
$p = implode(DIRECTORY_SEPARATOR, ["dir1", "dir2", "filename"]);
echo "p: " . $p . "\n";

// You should always use implode() with DIRECTORY_SEPARATOR instead of
// concatenating '/' or '\' manually. In addition to providing portability,
// this approach will also normalize paths.
echo implode(DIRECTORY_SEPARATOR, ["dir1//", "filename"]) . "\n";
echo implode(DIRECTORY_SEPARATOR, ["dir1/../dir1", "filename"]) . "\n";

// dirname() and basename() can be used to split a path to the
// directory and the file.
echo "Dir(p): " . dirname($p) . "\n";
echo "Base(p): " . basename($p) . "\n";

// We can check whether a path is absolute.
echo (strpos("dir/file", DIRECTORY_SEPARATOR) === 0 ? "true" : "false") . "\n";
echo (strpos("/dir/file", DIRECTORY_SEPARATOR) === 0 ? "true" : "false") . "\n";

$filename = "config.json";

// Some file names have extensions following a dot. We
// can split the extension out of such names with pathinfo().
$ext = pathinfo($filename, PATHINFO_EXTENSION);
echo $ext . "\n";

// To find the file's name with the extension removed,
// use pathinfo() with PATHINFO_FILENAME.
echo pathinfo($filename, PATHINFO_FILENAME) . "\n";

// realpath() finds an absolute path. It returns false if the path
// cannot be resolved.
$rel = realpath("a/b/t/file");
if ($rel === false) {
    echo "Error: Unable to resolve path\n";
} else {
    echo $rel . "\n";
}

$rel = realpath("a/c/t/file");
if ($rel === false) {
    echo "Error: Unable to resolve path\n";
} else {
    echo $rel . "\n";
}

To run the program, save it as file_paths.php and use php:

$ php file_paths.php
p: dir1/dir2/filename
dir1/filename
dir1/filename
Dir(p): dir1/dir2
Base(p): filename
false
true
json
config
/path/to/current/directory/a/b/t/file
Error: Unable to resolve path

Note that the output may vary depending on your current working directory and file system structure. The realpath() function will only work for existing files and directories.

PHP doesn’t have an exact equivalent to Go’s filepath.Rel(), but you can achieve similar functionality by using realpath() and string manipulation if needed.

Remember that PHP uses forward slashes (/) for paths on all operating systems when using most filesystem functions, but it’s still a good practice to use DIRECTORY_SEPARATOR for maximum portability.