How to improve security

I'd like to improve security of my website. Currently, the download filename is passed to the download script. The filenames are stored in a database table with an index number (primary key). I'd like to pass that index number to the download script instead of the filename and do a lookup in the download script but any sql code before the headers introduces problems with changes in md5sums of the downloaded files. Does anyone have any ideas n how to accomplish this?
Here's my download script:

<?php

function mydloader($l_filename=NULL)  {

    if( isset( $l_filename ) ) {
        $filename = preg_replace("/\s+/u", " ", $l_filename);
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
            {
            if ($ext == '.iso')
                header('Content-Type: application/x-cd-image');
            elseif ($ext =='.gz')
                header('Content-Type: application/zip');
            else
                header('Content-Type: octet-stream'); 
            }
        header('Content-Length: ' .filesize($filename));
        header("Content-Disposition: attachment; filename={$filename}");
        header('Pragma: no-cache');
        header('Expires: 0');        
        readfile($filename);


        $php_scripts = '../../php/';
        require $php_scripts . 'PDO_Connection_Select.php';
        require $php_scripts . 'GetUserIpAddr.php';

        $ip = GetUserIpAddr();
        if (!$pdo = PDOConnect("foxclone_data"))   {    
               exit;
        }

        $test = $pdo->query("SELECT lookup.id FROM lookup WHERE inet_aton('$ip') >= lookup.ipstart AND inet_aton('$ip') <= lookup.ipend");
        $ref = $test->fetchColumn();
        $ref = intval($ref);

        $ext = pathinfo($l_filename, PATHINFO_EXTENSION);
        $stmt = $pdo->prepare("INSERT INTO download (`address`, `filename`,`ip_address`, `lookup_id`) VALUES (?, ?, inet_aton('$ip'),?)");
        $stmt->execute([$ip, $ext,$ref]) ; 


      }

    else {
        echo "isset failed";
        }  
}
mydloader($_GET["f"]);  // passed from download page
exit;

Thanks in advance