Search code examples
phpfiledirectorytransfer

I want to search a directory for multiple files using PHP and start a download them over HTTP


Just to start, I'm a PHP noob.

I have an Apache server which hosts my files. I have a device which can only point to one PHP file. What I need it to do is have my PHP file read in the name of the file I want to download, and point it towards the directory it is stored. Currently, I have it pointing to one file, but I need it to be able to point to multiple. Is this possible in PHP?

Here's what I have so far:

<?php 
$file_name = 'file.img';
$size = filesize($file_name);
$file_url = 'http://192.168.0.5/' . $file_name;
header("Content-length: $size");
header("Content-Type: text/plain");
header("Content-Transfer-Encoding: binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);?>

Edit: The commands I want to input in order to download the file are close enough to as follows:

cmd=download+-a+$$.img+altimage
cmd=download+-a+$$.conf+altconfig

and the download directory is the .php file. I am open to other suggestions in how to do this.

Edit2: Here's what an exact sample URL is:

 myserver.com/cgi-bin/va/cmd?hdl+fullconfig.ini+altconfig

the hdl is a predefined function which points to the download directory, in order to download the file from the server, so the layout of what you mean isn't exactly the same.


Solution

  • I have trouble understanding what exactly you're trying to do, but I guess that you want a user to be able to download multiple files. If that is correct, here is one way to achieve this:

    You can let PHP create a ZIP archive using the ZIP extension. For it to work, you have to load the extension php_zip.dll inside your php.ini.

    $ZIP = new ZipArchive();
    
    // Use the current time as the filename to prevent two users to use the same file
    $ZIPName = microtime().".zip";
    
    // Create a new ZIP file
    $ZIP->open($ZIPName, ZIPARCHIVE::CREATE);
    
    // Loop through all files - $Files needs to be an array with the names of the files you want to add, including the paths
    // basename() will prevent the creation of folders inside the ZIP
    foreach ($Files as $File) {
        $ZIP->addFile($File, basename($File));
    }
    
    // Close the archive
    $ZIP->close();
    
    // Send the archive to the browser
    readfile($ZIPName);
    

    I hope this is what you were looking for.