Change the target of a symlink with PHP
Asked Answered
A

3

6

How can I change the target of a symlink with PHP? Thanks.

Ajaajaccio answered 23/3, 2010 at 4:1 Comment(0)
T
12

You can delete the existing link using unlink function and recreate the link to the new target using the symlink function.

symlink($target, $link);
.
.
unlink($link);
symlink($new_target, $link);

You need to do error checking for each of these.

Thea answered 23/3, 2010 at 4:5 Comment(3)
+1 - this is much better than writing the shell stuff yourself.Mechelle
okay, i was just seeing if there was a way around having to unlink and then recreate the symlink. thanks!Ajaajaccio
This means that the link is unavailable for a (short) time... Dangerous :-(Knighthead
M
3

PHP can execute shell commands using shell_exec or the backtick operator.

Hence:

<?php
`rm thelink`;
`ln -s /path/to/new/place ./thelink`;

This will be run as the user which is running the Apache server, so you might need to keep that in mind.

Mechelle answered 23/3, 2010 at 4:4 Comment(2)
Shell commands should be avoided when there are built-in alternatives.Kippar
Replace ln -s with ln -sf (and remove rm) and this solution becomes better than the accepted solution, as it atomically (on linux/unix) replaces the target of the link, with no interruption. As it seems there is no PHP function/option to do that (symlink() has no force option).Knighthead
H
0

To do this atomically, without the risk of deleting the original symlink and failing to create the new one, you should use the ln system command like so:

system(
    'ln --symbolic --force --no-dereference ' .
        escapeshellarg($new_target) . ' ' .
        escapeshellarg($link),
    $relinked
);
if (0 === $relinked) {
    # success
}
else {
    # failure
}

The force flag is necessary to update existing links without failing, and no-dereference avoids the rookie mistake of accidentally putting a link inside the old symlink's target directory.

It's wise to chdir() to the directory that will contain $link if using relative paths.

Hanfurd answered 10/6, 2021 at 5:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.