How can I change the target of a symlink with PHP? Thanks.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.