无法从本地主机使用 PHP ftp_connect 连接到 FTP

2022-01-09 00:00:00 ftp centos php apache

我一直在尝试编写一些脚本来通过 FTP 从我在 CentOS 中的本地 Apache 下载文件,但我无法让它工作!

I I've been trying to make some script to download files through FTP from my localhost Apache in CentOS and I can't get it to work!

我使用的代码正是任何基本 ftp 请求所使用的代码:

The code I am using is the very one used by any basic ftp request:

<?php
$ip= FTP_IP_HERE;
$port='21';
$timeout='90';
$un='username';
$pw='password';

// Connect to ftp
$conn_id = ftp_connect($ip,$port,$timeout);

// Open a session to an external ftp site
$login_result = ftp_login ($conn_id, $un, $pw);

// Check open
if ((!$conn_id) || (!$login_result)) {
    print "FTP connection failed!";
    exit();
}

// turn on passive mode transfers
if (ftp_pasv($conn_id, true) == FALSE) {
    print "Passive FTP connection failed!";
    exit();
}

我在远程服务器上尝试了相同的脚本,它成功了!我不确定是要完成任何 apache 配置,还是 PHP 本身的限制.

I tried the same script on remote server and it worked! I am not sure if it is any apache configuration to be done, or a PHP limitation itself.

更新:

这是错误日志:

Warning: ftp_login() expects parameter 1 to be resource, boolean given in /var/www/html/ftp/FTP.php on line 16

Warning: ftp_get() expects parameter 1 to be resource, boolean given in /var/www/html/ftp/FTP.php on line 22
Falha ao enviar o arquivo test.pdf<br />Array
(
    [type] => 2
    [message] => ftp_get() expects parameter 1 to be resource, boolean given
    [file] => /var/www/html/ftp/FTP.php
    [line] => 22
)

Warning: ftp_close() expects parameter 1 to be resource, boolean given in /var/www/html/ftp/FTP.php on line 30

推荐答案

好的,我遇到了同样的问题,我找到了适合我的案例的解决方案.在此处发布以帮助他人.

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

我的 PHP 脚本会失败,但我可以通过命令行轻松地 FTP.我确认我的防火墙没有阻止脚本,并且我的日志中没有出现任何 PHP 错误...

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...

四处搜索后,我的问题似乎是 SELinux.我不想关闭它,所以我检查了 httpd_can_network_connect 的状态.

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 

如果你得到:

httpd_can_network_connect --> off

这可能是您的问题.

注意:

如果你已经有这个on:

httpd_can_network_connect --> on

SELinux is disabled

那么这不会解决您的问题...祝您找到解决方案好运.

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

修复

通过运行启用 httpd_can_network_connect:

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

注意:-P 设置策略,使其在重启后仍然存在

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

相关文章