Skip to content
PHP Logo

In the provided PHP code snippet, what is the purpose of using array keys in the $_POST array and how does it facilitate file downloads?

Using array keys in the $_POST array allows us to easily identify which file to download based on the key provided. This facilitates file downloads by providing a direct link to the file associated with the key, making it more efficient and organized.

php
<?php
if(isset($_POST['download'])) {
    $files = [
        'file1' => 'path/to/file1.pdf',
        'file2' => 'path/to/file2.pdf'
    ];

    $key = $_POST['download'];

    if(array_key_exists($key, $files)) {
        $file = $files[$key];
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        readfile($file);
        exit;
    }
}
?>