FTP TLS session reuse in PHP

56 views Asked by At

I am trying to send a file to an FTPS server.

$conn_id = ftp_ssl_connect($ftp_server, $ftp_port);
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
ftp_set_option($conn_id, FTP_USEPASVADDRESS, false);
ftp_pasv($conn_id, true);
ftp_put($conn_id, $dest_file, $source_file, FTP_BINARY);
ftp_close($conn_id);

This gives me this error

Warning: ftp_put(): Data connection must use cached TLS session

or sometimes, when I change what file I am uploading, it gives me these errors:

Warning: ftp_put(): SSL write failed
Warning: ftp_put(): SSL_shutdown failed
Warning: ftp_put(): File status okay; about to open data connection.

I found a similar issue with fix for python FTPS with Python ftplib - Session reuse required

It appears that the server wants the data connections to use the same TLS session as the control connection. I don't have control over the server I am uploading to. I have tested the server with lftp and ensured that it works.

Is it possible to fix this with php's built in FTP library or should I find another FTP library (eg. cURL)?

1

There are 1 answers

1
Samuel On BEST ANSWER

As @sammitch mentioned in the comments this is a known bug until PHP version 8.2.14 and 8.3.1


As upgrading the PHP version we are using is a longer term task I opted to use PHP's builtin cURL bindings for now.

$fhandle = fopen($source_file,"r");

$url = "ftp://$ftp_server/$dest_file";
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERNAME,$ftp_user);
curl_setopt($ch,CURLOPT_PASSWORD,$ftp_pass);
curl_setopt($ch,CURLOPT_PORT,$ftp_port);

curl_setopt($ch,CURLOPT_PROTOCOLS,CURLPROTO_FTP);
curl_setopt($ch,CURLOPT_FTP_SSL,CURLFTPSSL_TRY);

curl_setopt($ch,CURLOPT_UPLOAD,true);
curl_setopt($ch,CURLOPT_INFILE,$fhandle);
curl_setopt($ch,CURLOPT_INFILESIZE,fileSize($source_file));

$result = curl_exec($ch);
curl_close($ch);
fclose($fhandle);