Solution to PHP FTP connection problem in containerized environment
P粉302484366
P粉302484366 2023-08-28 23:03:17
0
1
475

I'm trying to containerize my PHP script.

But for some reason it cannot connect to my FTP server when running in a container.

Run the script on my local machine without any problems.

Dockerfile:

FROM php:8.1-cli EXPOSE 8080 COPY ./var/www/html/ WORKDIR /var/www/html ENTRYPOINT php -f serve.php

PHP script:

$ connection = ftp_connect(FTP_HOST, 21, 90); ftp_pasv($connection, true); if(ftp_login($connection, FTP_USERNAME, FTP_PASSWORD)) { $stream = fopen('data://text/plain,','r'); ftp_fput($connection, $filename, $stream); } ftp_close($connection);

After 90 seconds, it will give the following warning:

ftp_fput(): Connection timed out in /var/ www/html/ftp.php on line 16

I tried going into the container and installing the FTP client.

It gives me a similar timeout error - I can connect to the host, but running any command causes a pause.

I also tried running the container on a VPS to eliminate any local firewall/network issues.

But the problem still exists.

If you need further information to resolve the issue, please let me know.

P粉302484366
P粉302484366

reply all (1)
P粉775723722

Pay attention to the documentation of PHP'sftp_pasvfunction(emphasis mine):

Also note that you are not checking the status return value of theftp_pasvcall, so you won't notice whether the call actually succeeded (which it most likely won't). Therefore, your script will attempt to establish an active FTP connection. This does not work in containers (unless started with--network=host), since containers run in a private network via NAT on the host machine.

Solution: Log in first, then enable passive mode (also always check for error return values; many old functions from the PHP standard library do not throw exceptions but rely on error return values):

if (ftp_login($connection, FTP_USERNAME, FTP_PASSWORD)) { if (ftp_pasv($connection, true) === false) { throw new \Exception("无法启用被动模式") } $stream = fopen('data://text/plain,','r'); ftp_fput($connection, $filename, $stream); }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!