PHP code example of dangoodman / deferred

1. Go to this page and download the library: Download dangoodman/deferred library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dangoodman / deferred example snippets


    function download($url, $toFile)
    {
        // Temporary increase memory limit for this function
        // $restoreMemoryLimit automatically called upon function exit
        $prevMemoryLimit = ini_get('memory_limit');
        ini_set('memory_limit', '256M');
        $restoreMemoryLimit = new Deferred(function() use($prevMemoryLimit) {
            ini_set('memory_limit', $prevMemoryLimit);
        });

        $contents = file_get_contents($url);
        if (!$contents) {
            throw new \RuntimeException("Couldn't fetch url contents");
        }

        if (file_put_contents($toFile, $contents) === false) {
            throw new \RuntimeException("Couldn't save url contents to file '{$toFile}'");
        }

        return $contents;
    }

    function downloadWithouDeferred($url, $toFile)
    {
        $prevMemoryLimit = ini_get('memory_limit');
        ini_set('memory_limit', '256M');

        $contents = file_get_contents($url);
        if (!$contents) {
            ini_set('memory_limit', $prevMemoryLimit);
            throw new \RuntimeException("Couldn't fetch url contents");
        }

        if (file_put_contents($toFile, $contents) === false) {
            ini_set('memory_limit', $prevMemoryLimit);
            throw new \RuntimeException("Couldn't save url contents to file '{$toFile}'");
        }

        ini_set('memory_limit', $prevMemoryLimit);

        return $contents;
    }