使用 PHP 复制文件时保留文件权限和所有者

Keep file permission and owner when copying file with PHP

使用PHP复制文件时如何保留文件权限和所有者?

复制文件的代码:

$source = CSS . 'customers' . DS . 'source.css';
$destination = CSS . 'customers' . DS . 'destination.css';

if(!@copy($source, $destination)) {
    $errors= error_get_last();
    echo "COPY ERROR: ".$errors['type'];
    echo "<br />\n".$errors['message'];
}

输出:

-rwxrwxrwx    1 myuser  admin  7145 11 Nov 20:02 source.css
-rw-r--r--    1 daemon  admin  7145 19 Nov 16:27 destination.css

只有 admin/root 可以更改文件的所有者。

  • Apache 运行 作为用户 apache 或守护进程,不能更改所有权。
  • CLI 程序运行 作为用户不能更改所有者
  • CLI 程序 运行 作为 root 可以 更改所有者

您可以做的是将文件权限设置为组或所有用户可读。

exec( 'chmod 664 ' . $filename );  // Group only
exec( 'chmod 666 ' . $filename );  // All users

文件名是带路径或相对于脚本路径的绝对文件名!