Download web file for PHP function

Asked

Viewed 99 times

1

I am using PHP’s Ziparchive class to unzip files from my directory, but my file is updated weekly at the same web address. I tried to do it this way:

<?php

$zip = new ZipArchive;
if ($zip->open('http://example.com/file.zip') === TRUE) {
    $zip->extractTo('C:/xampp/htdocs');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
} ?>

And he falls right out of else returning failure. Is there any class that downloads the file to my directory and then uses Ziparchive correctly?

  • 2

    ftp if authentication is required, or curl or even a code of a package http://docs.guzzlephp.org/en/stable/ then everything depends on ... the open do ZipArchive opens a local directory file.

  • Thanks @Virgilionovic searching about Curl I managed to solve 100% of my problem.

1 answer

2


Using Virgilio’s tip and using curl I was able to adapt my code that met all my needs, maybe serve to those who seek the same:

  <?php 
        $url = "http://www.example.com/file.zip"; // URL of what you wan to download
        $zipFile = "file.zip"; 
        $extractDir = "extracted"; 
        $zipResource = fopen($zipFile, "w");
    
        // Get The Zip File From Server
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        curl_setopt($ch, CURLOPT_FILE, $zipResource);
        curl_setopt($ch, CURLOPT_COOKIEFILE, "");
    
        $page = curl_exec($ch);
    
        if(!$page) {
            echo "Error :- ".curl_error($ch);
        }
    
        curl_close($ch);
    
        /* Open the Zip file */
        $zip = new ZipArchive;
        $extractPath = $extractDir;
    
        if($zip->open($zipFile) != "true"){
            echo "Error :- Unable to open the Zip File";
        } 
    
        /* Extract Zip File */
        $zip->extractTo($extractPath);
        $zip->close();
    
        die('Your file was downloaded and extracted, go check.');
    ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.