Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP chown function

Just as on Linux, chown (change owner) in PHP changes the owner of the specified file or directory.

Attention: Using the chown function to change the owner of a file or directory can have implications on security and file access. It’s important to exercise caution when making changes. Please note that this function does not work on Windows.
Description / Descripción
chown(string $filename, mixed $user): bool

Try to change the owner of $filename as the user $user.

Only the superuser can change the owner of a file or directory.

Parameters

$filename – The path to the file.

$user – A username or user ID.

Returns

It will return true on success.

It will return false in case of an error.


Applying PHP chown recursively

Something to keep in mind is that we cannot run chown recursively with PHP, so we will need to create a function that fulfills this purpose.

On this occasion, I thought of testing ChatGPT to see how well it performs. The following code is generated with ChatGPT:

función para cambiar recursivamente el propietario de un fichero
function cambiarPropietarioRecursivo($directorio, $propietario) {
    if (!is_dir($directorio)) {
        return;
    }

    // Cambiar propietario del directorio actual
    chown($directorio, $propietario);

    $archivos = scandir($directorio);
    foreach ($archivos as $archivo) {
        if ($archivo === '.' || $archivo === '..') {
            continue;
        }

        $rutaArchivo = $directorio . '/' . $archivo;
        if (is_dir($rutaArchivo)) {
            cambiarPropietarioRecursivo($rutaArchivo, $propietario);
        } else {
            chown($rutaArchivo, $propietario);
        }
    }
}

// Uso de la función para cambiar propietarios de forma recursiva
$rutaDirectorio = '/ruta/al/directorio';
$nuevoPropietario = 'nuevo_usuario';

cambiarPropietarioRecursivo($rutaDirectorio, $nuevoPropietario);

It is worth mentioning that the function I created makes a lot of sense. It checks if it is a directory first and also uses the scandir function to get the files in the directory. However, I’m not sure if scandir returns “.” and “..”, but the function seems to fulfill the purpose we wanted.

Examples of simple chown commands.

The following example changes the owner of a directory, but does not change the owner of its children (files and directories).

Cambia el propietario de un directorio
$rutaDirectorio = '/ruta/al/directorio';
$nuevoPropietario = 'nuevo_usuario';

if (chown($rutaDirectorio, $nuevoPropietario)) {
    echo "El propietario del directorio se ha cambiado exitosamente.";
} else {
    echo "No se pudo cambiar el propietario del directorio.";
}

Changing the owner of a file.

Utilizando el nombre de usuario
$ruta = '/ruta/al/archivo.txt';
$nuevoPropietario = 'nuevo_usuario';

if (chown($ruta, $nuevoPropietario)) {
    echo "El propietario del archivo se ha cambiado exitosamente.";
} else {
    echo "No se pudo cambiar el propietario del archivo.";
}
Utilizando la id de usuario
$ruta = '/ruta/al/archivo.txt';
$nuevoPropietario = 1001; // ID de usuario

if (chown($ruta, $nuevoPropietario)) {
    echo "El propietario del archivo se ha cambiado exitosamente.";
} else {
    echo "No se pudo cambiar el propietario del archivo.";
}

Exercise

Create a folder with 5 elements in the following way:

  • folder 1
    • file1
    • folder 2
      • file2
      • file3
      • file4

Use the function created in the recursive function example in such a way that if it is a file, change its owner as well. To do this, you will need to create functions and modify the cambiarPropietarioRecursivo function.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category