Library contents

PHP symlink and readlink

Create a relative symbolic link and read its stored target.

A simple example

symlink and readlink

  1. Start with Link named alias points to a.txt
  2. Do this Read the symbolic link target
  3. Result a.txt
A symbolic link stores a target path. The target supplies the contents when the link is followed.

Syntax

PHP 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.php

Follow 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.

Resultmaster.txt
lesson.php
<?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);
}
Output
master.txt

The relative target is resolved from the directory containing the shortcut.

Advertisements

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?

GivenFile contents “clay”
Worked resultclay

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?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

This example requires symbolic-link support and permission to create links.

Documentation for symlink and readlink