如何在不列出目录的情况下发送FTP命令,或使用curl传输文件?

How to send FTP commands without listing directory, or transferring files with curl?

提问人:root66 提问时间:10/26/2015 最后编辑:Martin Prikrylroot66 更新时间:10/26/2015 访问量:682

问:

我正在尝试向 ProFTPD 服务器发送一些标准命令,curl 总是发送命令,我的命令结果被响应覆盖。LISTLIST

curl_setopt($curl, CURLOPT_URL, "ftp://domain.xyz:21");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_QUOTE, array('PWD'));
$result=curl_exec($curl);

日志文件包含:

> PWD
< 257 "/" is the current directory
> PASV
* Connect data stream passively
< 227 Entering Passive Mode (xxx,xxx,xxx,xxx,xxx,xxx).
* Hostname was NOT found in DNS cache
*   Trying xxx.xxx.xxx.xxx...
* Connecting to xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx) port 39794
* Connected to xyz (xxx.xxx.xxx.xxx) port 21 (#0)
> TYPE A
< 200 Type set to A
> LIST
< 150 Opening ASCII mode data connection for file list

我想得到“257”/“是当前目录”行。

更新:
有一个选项,可以停用该命令,但我仍然无法获得该命令的响应,即使使用 .
CURLOPT_NOBODYLISTPWDCURLOPT_CUSTOMREQUEST

我不能使用 PHP 的 FTP 命令,因为 Windows 上的 PHP 没有该功能。是否有任何其他具有 TLS 支持和上传/下载进度处理程序的 FTP 库?ftp_ssl_connect

php 卷曲 ftp

评论


答:

2赞 Martin Prikryl 10/26/2015 #1

我不认为 curl 是为这样的任务而设计的。

话虽如此,您可以通过启用日志记录并解析日志中的响应来破解它。

function curl_ftp_command($curl, $command)
{
    // Create a temporary file for the log
    $tmpfile = tmpfile();
    // Make curl run our command before the actual operation, ...
    curl_setopt($curl, CURLOPT_QUOTE, array($command));
    // ... but do not do any operation at all
    curl_setopt($curl, CURLOPT_NOBODY, 1);
    // Enable logging ...
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    // ... to the temporary file
    curl_setopt($curl, CURLOPT_STDERR, $tmpfile);

    $result = curl_exec($curl);

    if ($result)
    {
        // Read the output
        fseek($tmpfile, 0);
        $output = stream_get_contents($tmpfile);

        // Find the request and its response in the output
        // Note that in some some cases (SYST command for example),
        // there can be a curl comment entry (*) between the request entry (>) and
        // the response entry (<)
        $pattern = "/> ".preg_quote($command)."\r?\n(?:\* [^\r\n]+\r?\n)*< (\d+ [^\r\n]*)\r?\n/i";
        if (!preg_match($pattern, $output, $matches))
        {
            trigger_error("Cannot find response to $command in curl log");
            $result = false;
        }
        else
        {
            $result = $matches[1];
        }
    }

    // Remove the temporary file
    fclose($tmpfile);

    return $result;
}

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "ftp://domain.xyz:21");

echo curl_ftp_command($curl, "PWD");