Is it possible to download the files in a directory using curl in PHP?

Dani AI

Generated

Short answer for practical use: if you control the server that holds the files, the simplest and most reliable pattern is to create a server-side endpoint that packages the directory (ZIP) and serves that single archive — then use curl to download one file instead of enumerating and pulling many files. That avoids brittle parsing of directory listings and works regardless of FTP/HTTP listing formats. pointed you toward FTP+parsing; 's question about whether files are local is the right pivot: choose the approach below based on where the files live.

A compact server-side workflow (PHP): create a ZIP from the target directory, stream it to the client, then remove the temporary ZIP. Example sketch:

<?php
$dir = '/path/to/dir';
$tmp = tempnam(sys_get_temp_dir(), 'dl_') . '.zip';
$zip = new ZipArchive();
if ($zip->open($tmp, ZipArchive::CREATE) === TRUE) {
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($it as $f) {
        if ($f->isFile()) {
            $zip->addFile($f->getRealPath(), substr($f->getRealPath(), strlen($dir)+1));
        }
    }
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="download.zip"');
    readfile($tmp);
    unlink($tmp);
    exit;
}

If you cannot add server-side code and must work against a remote FTP server: prefer SFTP/FTPS when possible for security; use a proper SFTP client library (phpseclib or ext-ssh2) rather than brittle parsing of LIST output. If you must use curl+FTP, fetch a machine-readable name list, then download files (consider curl_multi for parallel fetches).

Troubleshooting/cautions: watch memory and execution time (use temp files and increase limits where needed), ensure correct transfer mode (binary for non-text), handle permissions and traversal safely, and rate-limit downloads to avoid hammering the server. For large directories the ZIP-on-server pattern is usually the fastest and simplest.

Recommended Answers

All 2 Replies

Yes, you can. Through the FTP protocol. Here's a sample directory listing, then with regards to downloading the contents, you can use ftp commands to download the contents after parsing the directory list

$curl = curl_init();
$ftpURL = "ftp://localhost/"
$ftpUsername = "username"
$ftpPassword = "password"

curl_setopt($curl, CURLOPT_URL, $ftpURL);
curl_setopt($curl, CURLOPT_USERPWD, $ftpUsername . ":" . $ftpPassword);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);

//Parse your result then use ftp to download the content
Member Avatar for Member #120589

Are these files on your server?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.