Recursion In PHP 🌀

Published Sep 12 2023

recursion
php
download

I wanted a way to iterate over a nested associative data structure containing file URLs, and programmatically download each file through the command line. Additionally, I aimed to maintain the folder structure once the files were downloaded onto my computer.

This is how I accomplished this. In the example below, each key of the associative array represents a folder, and each corresponding value represents the URL for downloading.

#!/usr/bin/env php

<?php

$files = [
    'Folder 1' => [
        'Nested Folder 1' => [
            'File 1' => 'https://embed-ssl.wistia.com/deliveries/1234/file.mp4',
            'File 2' => 'https://embed-ssl.wistia.com/deliveries/5678/file.mp4',
        ],
    ]
];

initiateDownload($files);

function initiateDownload($files)
{
    foreach ($files as $path => $value) {
        findAndDownload($path, $value);
    }
}

function findAndDownload($path, $val, $currentPath = '')
{
    foreach ($val as $key => $value) {
        $location = ($currentPath === '') ? $key : $currentPath.'/'.time().'_'.$key;

        if ($path) {
            $location = $path.'/'.$location;
        }

        if (is_array($value)) {
            if (!file_exists($location)) {
                mkdir($location, 0777, true);
            }

            findAndDownload(0, $value, $location);
        } else {
            $filename = basename($value);
            file_put_contents($location.'_'.$filename, file_get_contents($value));
        }
    }
}

© 2025 Elvis Magagula, All rights reserved