【问题标题】:How to send FTP commands without listing directory, or transferring files with curl?如何在不列出目录或使用 curl 传输文件的情况下发送 FTP 命令?
【发布时间】:2015-10-25 23:16:40
【问题描述】:

我正在尝试向 ProFTPD 服务器发送一些标准命令,而 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

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

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

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

【问题讨论】:

    标签: php curl ftp


    【解决方案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");
    

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多