Uploading a file with FTP

Every now and again, you'll be asked to generate a file—perhaps from a database export, or maybe some system logs. Most of the time, you'll be asked to e-mail that file to some location, but sometimes, you'll be asked to upload it to an FTP folder the client has access to. We're going to take a recipe from a previous chapter (Generating a CSV from a database result from Chapter 6, Working with Databases), and adapt it so that it uploads to an FTP location rather than stream an output.

Getting ready

  1. We're going to be pulling some values from a database. To do that, we'll need a table to pull data from. The following is the schema for that table. Copy the following into your database:
    CREATE TABLE `users` (
      `user_id` int(11) NOT NULL AUTO_INCREMENT,
      `user_firstname` varchar(255) NOT NULL,
      `user_lastname` varchar(255) NOT NULL,
      `user_email` varchar(255) NOT NULL,
      PRIMARY KEY (`user_id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;# MySQL returned an empty result set (i.e. zero rows).
    
    INSERT INTO `users` (`user_id`, `user_firstname`, `user_lastname`, `user_email`) VALUES
    (1, 'Rob', 'Foster', '[email protected]'),
    (2, 'Lucy', 'Welsh', '[email protected]'),# 2 rows affected.
  2. Go to Chapter 6, Working with Databases, and copy out the code from the Generating a CSV from a database result recipe; then return here for further instructions.

How to do it...

We're going to amend one file from the Generating a CSV from a database result recipe, that is, /path/to/codeigniter/application/controllers/export.php. This is the export controller from Chapter 6, Working with Databases. We're going to use it as the basis for this recipe. It will grab some data from the database that eventually generates a CSV for us.

  1. Open export.php for editing and amend it to reflect the following code snippet (changes are highlighted):
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed'),
    
    class Export extends CI_Controller {
      function __construct() {
        parent::__construct();
        $this->load->helper('url'),
        $this->load->helper('file'),
        $this->load->library('ftp'),
        $this->load->dbutil();
      }
    
      public function index() {
        redirect('export/csv'),
      }
    
      public function csv() {
        $query = $this->db->query("SELECT * FROM users");
    
        $delimiter = ",";
        $newline = "
    ";
    
        $data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
        $filename = 'myfile.csv';
        $path = './'.$filename;	
    
        if (! write_file($path, $data)) {
          echo 'Cannot write file - permissions maybe?';
          exit;
        }
    
        $config['hostname'] = 'your-hostname';
        $config['username'] = 'your-username';
        $config['password'] = 'your-password';
        $config['debug'] = TRUE;
    
        $this->ftp->connect($config);
        $this->ftp->upload($path, '/dir_on_ftp/'.$filename, 'ascii', 0755);
        $this->ftp->close();
      }
    }

    There are some variables here that you should change to reflect the settings of your FTP environment such as:

    $config['hostname'] = 'ftp.example.com';
    $config['username'] = 'your-username';
    $config['password'] = 'your-password';

    ...and the string dir_on_ftp in:

    $this->ftp->upload($path, '/dir_on_ftp/'.$filename, 'ascii', 0755);

How it works...

As you would expect from a new recipe, there are some changes in the normal export controller that we've used in Chapter 6, Working with Databases. These changes are necessary to support the FTP helper in its job of uploading a file to an FTP server. Let's take a look at what's going on.

First, we load the helpers we'll need--url, file, and FTP--in the Exporter controllers constructor to ensure that this export controller has the right support necessary to make the file transfer.

function __construct() {
    parent::__construct();
    $this->load->helper('url'),
    $this->load->helper('file'),
    $this->load->library('ftp'),    
    $this->load->dbutil();    
  }

Everything then follows the functionality of the previous controller (from Chapter 6, Working with Databases) ,that is, fetching a result set from the database table and using the CodeIgniter dbutil function, csv_from_result(), to generate a file for us. It's placed on the server by write_file() using the location defined in $path.

Then the FTP functionality kicks in. We define the login settings for the FTP server we want to write the file to--you can and probably should put these in your own config file (also explained in this chapter, see the Making your own configuration files and using the settings recipe), but for now, we'll define them here as it's easier to explain one thing at a time. The settings are fairly obvious until you see the $config['debug'] array setting. debug allows error reports to be displayed to you, the developer. Obviously, in a live production environment, you definitely want that set to be FALSE to prevent any sensitive and important information being shown.

Anyways, using the login settings that we have defined in our $config array, we attempt to connect to the FTP server and try to upload a file, as shown in the following code snippet:

$this->ftp->connect($config);
$this->ftp->upload($path, '/dir_on_ftp/'.$filename, 'ascii', 0755);

If all goes well, the file should be uploaded to your server. Log in with an FTP client and take a look to see if it's there--if it's not check that you're using the correct FTP settings and that the path you're writing to on the FTP server is writable and actually exists, that is, that the path defined here in bold exists:

$this->ftp->upload($path, '/dir_on_ftp/'.$filename, 'ascii', 0755);

An interesting point is the two function arguments at the end of the preceding upload() function: ascii and 0755. These state that we're encoding the file transfer as ascii (which is plain text) and setting its file permissions to 0755. This can also be defined in the config array if you wish.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.41.187