What are the best practices for handling file extraction using ZipArchive in PHP?

When handling file extraction using ZipArchive in PHP, it is important to ensure proper error handling, close the ZipArchive object after use, and securely handle user input to prevent security vulnerabilities such as directory traversal attacks.

$zipFile = 'example.zip';
$extractPath = 'extracted_files/';

$zip = new ZipArchive;
if ($zip->open($zipFile) === TRUE) {
    $zip->extractTo($extractPath);
    $zip->close();
    echo 'Files extracted successfully.';
} else {
    echo 'Failed to extract files.';
}