Search code examples
phpcsvftpfopen

Open text file on a FTP account with PHP


I'm trying to read a CSV file on a FTP account but the same code that I use for other accounts is not working anymore.

This new FTP account, when I connect to it using FileZilla, for example, an window saying things about a certificate is shown. I have to agree, than I can access the FTP files normally through the program. I imagine that this certificate thing is the cause of my problem.

This is the code that I'm using:

$filename = "ftp://$user:$pass@$host/filename.csv";

 $fh = fopen($filename, "r");

 while (!feof($fh)) {
    $line = fgets($fh);
    var_dump($line);
 }
 fclose($fh);

Is there a way to change my code to consider the requirements of this FTP account that involves a certificate?


Solution

  • I currently don't have a server to test but to allow invalid certificates (I assume that's the question) when using stream wrappers you need to create a proper stream context and pass it as fopen()'s 4th argument. The context options that apply are FTP and SSL. You probably want to set verify_peer to false.

    $context = stream_context_create([
        'ssl' => [
            'verify_peer'       => false,
            'verify_peer_name'  => false,
            'allow_self_signed' => true,
        ]
    ]);
    $fh = fopen($filename, 'r', false, $context);