Can't connect to FTP with PHP ftp_connect from localhost Can't connect to FTP with PHP ftp_connect from localhost apache apache

Can't connect to FTP with PHP ftp_connect from localhost


Ok, I had the same issue and I found the solution for my case. Posting it here to help others.

My PHP script would fail but I could easily FTP via command line. I verified my firewall wasn't blocking the script and I was not getting any PHP errors in my log...

After searching around, it appeared my issue was SELinux. I didn't want to turn it off so I checked the status of httpd_can_network_connect.

Check your status by running:

getsebool httpd_can_network_connect 

If you get:

httpd_can_network_connect --> off

This may be your issue.

Note:

If you already have this on:

httpd_can_network_connect --> on

or

SELinux is disabled

Then this is not going to solve your issue... Good luck finding your solution.

The Fix

Enable httpd_can_network_connect by running:

setsebool httpd_can_network_connect=1

Test your script again and see if it works. This worked for me so I made sure to set a policy to keep this enabled.

setsebool -P httpd_can_network_connect=1

NOTE: -P sets the policy so it persists over a reboot


First make sure it's not an issue with your local firewall or something. Try to FTP from any other tool, e.g.

wget --user=username --password='password' ftp://FTP_IP_HERE/file_to_download

If wget fails to connect as well, it's a problem with your network settings.

If wget passes the test you can also try enabling verbose error reporting to see what's wrong with your PHP attemp by placing this at the top of your code:

<?phpini_set('display_errors',1);error_reporting(E_ALL|E_STRICT);

Finally, this might be also relevant to your case: Cannot connect with FTP server with PHP , ftp_connect()


Try '127.0.0.1' instead of 'localhost'

ftp_connect('127.0.0.1', 21);