Blog de programación, errores, soluciones

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

PHP unlink function

PHP unlink fulfills the function of deleting a file.

Description / Descripción
unlink(string $filename, resource $context = ?): bool

Parameters

$filename: Path to the file.

$context: Note: Support for context was added in PHP 5.0.0. For a description of contexts, refer to Streams. This refers to the STREAM from where I am trying to delete the file, is it a request through the HTTP, FTP protocol? What is it?

Returns

Returns true on success or false on failure. An E_WARNING level error will be generated if an error occurs.

PHP unlink example

If we ask chat GPT to give us an example, it will give us something like this.

PHP unlink example
if (file_exists($archivoAEliminar)) {
    if (unlink($archivoAEliminar)) {
        echo "El archivo '$archivoAEliminar' ha sido eliminado correctamente.";
    } else {
        echo "No se pudo eliminar el archivo '$archivoAEliminar'.";
    }
} else {
    echo "El archivo '$archivoAEliminar' no existe.";
}

Here we must clarify something, file_exists can give us problems, when you use file_exists you should keep in mind if it is a file that is added by a user through an upload or not.

In that case, we could have a very high number of files to use this option. In that case it is better to have the URL of the file in a database and check in it (file_exists would take a long time). Or if you want to use a redis for this functionality, among others.

Use file_exists only in cases where they are internal files, such as the page logo or things like that.

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