What are some best practices for handling file downloads and extraction in PHP?

When handling file downloads and extraction in PHP, it is important to ensure that the files are securely downloaded and extracted to prevent any security vulnerabilities. One best practice is to validate the file type before downloading and extracting it to prevent malicious files from being processed.

// Example of handling file download and extraction in PHP

$downloadedFile = 'example.zip';
$extractedPath = 'extracted/';

// Validate file type before downloading
if (pathinfo($downloadedFile, PATHINFO_EXTENSION) !== 'zip') {
    die('Invalid file type');
}

// Download the file
file_put_contents($downloadedFile, file_get_contents('http://example.com/example.zip'));

// Extract the downloaded file
$zip = new ZipArchive;
if ($zip->open($downloadedFile) === TRUE) {
    $zip->extractTo($extractedPath);
    $zip->close();
    echo 'File extracted successfully';
} else {
    echo 'Failed to extract file';
}