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

时间:2015-10-25 23:16:40

标签: php curl ftp

我尝试向ProFTPD-Server发送一些标准命令,curl总是发送LIST命令,LIST响应覆盖了我的命令结果。

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

我想得到&#34; 257&#34; /&#34;是目前的目录&#34;线。

更新:
有一个选项CURLOPT_NOBODY,它会停用LIST命令,但我仍然无法获得PWD命令的响应,即使CURLOPT_CUSTOMREQUEST也是如此

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

1 个答案:

答案 0 :(得分:2)

我不认为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");