PHP symlink and readlink
Create a relative symbolic link and read its stored target.
A simple example
symlink and readlink
- Start with Link named alias points to a.txt
- Do this Read the symbolic link target
- Result a.txt
Syntax
readlink($link)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpFollow a shortcut to the latest timetable
A station maintains one current timetable and publishes a shortcut beside it. Inspect the name stored in the shortcut and verify that it still leads readers to the master timetable.
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
$link = $base . '/today';
if (!touch($base . '/master.txt') || !symlink('master.txt', $link)) throw new RuntimeException('Cannot link');
if (is_link($link) && is_file($link)) echo readlink($link), PHP_EOL;
} finally {
foreach (['today', 'master.txt'] as $name) {
$path = $base . '/' . $name;
if (is_link($path) || is_file($path)) unlink($path);
elseif (is_dir($path)) rmdir($path);
}
rmdir($base);
}
master.txt
The relative target is resolved from the directory containing the shortcut.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. A desk makes a symbolic link named latest to the saved note. When a reader follows the link, which contents does it see?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. A desk makes a symbolic link named latest to the saved note. When a reader follows the link, which contents does it see?
What to watch for
This example requires symbolic-link support and permission to create links.