Showing posts with label Download. Show all posts
Showing posts with label Download. Show all posts

Saturday 30 December 2017

How to download and Extract Uncompress zip / gz file from URL in PHP


File zip / gz download from URL

ini_set('display_errors', 1);
$dbname = 'db_'.date('Ymdhis').".gz";
$url = 'http://www.domainname.com/backups/bkp30122017.gz';
file_put_contents($dbname, fopen($url, 'r'));

Extract / Uncompress GZ / ZIP file

try{
    //This input should be from somewhere else, hard-coded in this example
    $file_name = $dbname;
    // Raising this value may increase performance
    $buffer_size = 4096; // read 4kb at a time
    $out_file_name = str_replace('.gz', '.sql', $file_name);
    // Open our files (in binary mode)
    $file = gzopen($file_name, 'rb');
    $out_file = fopen($out_file_name, 'wb');
    // Keep repeating until the end of the input file
    while (!gzeof($file)) {
        // Read buffer-size bytes
        // Both fwrite and gzread and binary-safe
        fwrite($out_file, gzread($file, $buffer_size));
    }
    // Files are done, close files
    fclose($out_file);
    gzclose($file);
} catch (Exception $ex) {
    echo $ex->getMessage();
}

Tuesday 30 August 2016

How to Get / Upload / Delete / Update file in using SFTP / FTP in PHP, Codeigniter Library

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol

Here is a small code on how to read the folder and download all files:

Controller.php

      $params = array('host' => $shopdata->ftphost, 'port' => 22);
            $this->load->library('sftpconnection', $params);
         
            $this->sftpconnection->login($shopdata->ftpuser, $shopdata->ftppass);
            //$this->sftpconnection->uploadFile("http://localhost/shopify/inventorymanagement/uploads/sku.csv", "/codetest/test.csv");
            //$result = $this->sftpconnection->scanFilesystem("/TEST/DESADV");
            $result = $this->sftpconnection->downloadFiles("$folder","/TEST/DESADV/");
            pre($result);
Create Library file : Sftpconnection.php

<?php
/*
  Sftp connection in PHP
  Created: Feb 18th, 2016
  Modified: Feb 18th, 2016
  Version: 1.0.1
  Auther : Jaydip Kanasagra
 */

//this function is just to make the code a little cleaner
class Sftpconnection {

    private $connection;
    private $sftp;

    public function __construct($config) {
        $host = $config['host'];
        $port = $config['port'];
        $this->connection = @ssh2_connect($host, $port);
        if (!$this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password) {
        if (!@ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
            "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (!$this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (!$stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }

    public function receiveFile($remote_file, $local_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (!$stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents($local_file, $contents);
        @fclose($stream);
    }
 
    public function downloadFiles($local_dir, $remote_dir) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_dir";
        $downloadedfiles = $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
     
        foreach ($files as $file)
        {
            $currentdir = $this->getCurrentdirfiles('uploads/ftpfiles/TEST/JAYDIP/');
            if(in_array($file, $currentdir)){
                continue;
            }
         
            echo "Copying file: $file<br>";
            if (!$remote = @fopen("ssh2.sftp://{$sftp}{$remote_dir}{$file}", 'r'))
            {
                echo "Unable to open remote file: $file\n";
                continue;
            }

            if (!$local = @fopen($local_dir . $file, 'w'))
            {
                echo "Unable to create local file: $file\n";
                continue;
            }

            $read = 0;
            $filesize = filesize("ssh2.sftp://{$sftp}/{$remote_dir}{$file}");
            while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
            {
                $read += strlen($buffer);
                if (fwrite($local, $buffer) === FALSE)
                {
                    echo "Unable to write to local file: $file\n";
                    break;
                }
            }
            $downloadedfiles[] = $file;
            fclose($local);
            fclose($remote);
        }

        return $downloadedfiles;
    }

    function scanFilesystem($remote_file) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_file";
        $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        return $files;
    }
 
    function getCurrentdirfiles($dir){
        //$dir = "ftpfiles/TEST/JAYDIP/";
        $listfiles = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $listfiles[] = $file;
                }
            }
        }
        closedir($handle);
        return $listfiles;
    }

}

?>