【问题标题】:SFTP a HTML made on the fly file to an external severSFTP 将动态生成的 HTML 文件发送到外部服务器
【发布时间】:2012-12-19 17:42:55
【问题描述】:

我正在尝试对动态制作的 HTML 文件(使用文件放置内容)和 shh2 库进行 SFTP。

这是我到目前为止所得到的,apache 报告它无法发送,因为本地磁盘上不存在该文件:

$pageBody = '<body>
    <div id="canvas_container">
        <canvas id="designer_canvas" width="430" height="415">
        </canvas>
    </div>
<div style="display:none" id="share_design_details">
<li>'.$mc1.'</li><li>'.$mc1.'</li><li>'.$mc2.'</li><li>'.$sp.'</li><li>'.$p.'</li><li>'.$c.'</li></div>

<div id="test">This design is called : '.$designName.'</div></body>' ; 


$newFile = file_put_contents('newfile.html',$pageBody);
$connection = ssh2_connect('myhost.com', 22);
ssh2_auth_password($connection, 'myuser', 'mypass');

$sftp = ssh2_sftp($connection);
ssh2_scp_send($connection, $newFile, $newFile, 0644);

【问题讨论】:

  • php.net/file_put_contents 返回真或假,但 ssh2_scp_send() 需要文件路径
  • 如何修改发送以便上传文件而无需在本地磁盘上创建文件?
  • 我不认为你可以。我会说只是将文件名传递给它,然后删除它
  • 干杯,如果有办法,我会保持打开状态,但将其作为答案发布,因为它可能对其他人有用。
  • 参见示例 #1 通过 SFTP 在php.net/manual/en/function.ssh2-sftp.php 打开文件 — 只需打开文件进行写入而不是读取

标签: php html ftp sftp


【解决方案1】:

我自己会使用 phpseclib,一个纯 PHP SFTP 实现。例如。

<?php
include('Net/SFTP.php');

//Define content
$pageBody = 'CONTENT HERE';

//Connect to SFTP host
$sftp = new Net_SFTP('myhost.com', 22);
$sftp->login('myuser', 'mypass');

//Send the file
$sftp->put('/tmp/temp.html', $pageBody);
?>

更便携,也更容易使用。

【讨论】:

    【解决方案2】:

    ssh2_scp_send() 函数需要本地和远程文件的文件路径。

    http://php.net/manual/en/function.ssh2-scp-send.php

    file_put_contents() 函数返回写入文件的字节数,而不是文件路径。

    http://php.net/manual/en/function.file-put-contents.php

    因此,您的 ssh2_scp_send() 应如下所示,其中目标服务器上的目标目录为 /tmp

    ssh2_scp_send($connection, 'newfile.html', '/tmp/newfile.html', 0644);
    

    我认为不可能上传尚不存在的文件,因为您实际上是直接写入目标服务器而不是上传文件。

    我会在发送后使用 unlink() 函数删除文件。

    http://php.net/manual/en/function.unlink.php

    所以你的完整逻辑如下:

    //Define content
    $pageBody = 'CONTENT HERE';
    
    //Create the file
    $newFile = file_put_contents('temp.html', $pageBody);
    
    //Connect to SFTP host
    $connection = ssh2_connect('myhost.com', 22);
    ssh2_auth_password($connection, 'myuser', 'mypass');
    $sftp = ssh2_sftp($connection);
    
    //Send the file
    ssh2_scp_send($connection, 'temp.html', '/tmp/temp.html', 0644);
    
    //Delete the local file
    unlink('temp.html);
    

    【讨论】:

      【解决方案3】:

      完全未经测试,但通常写入 SSH 连接(请注意,在 shell 下)使其可用于另一端。考虑到这一点,运行一个命令,将其放在另一侧的正确位置,然后写入。

      $stream = ssh_exec('cat > some/file');
      $result = fwrite($stream, $pageBody);
      

      【讨论】:

        猜你喜欢
        • 2018-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        • 1970-01-01
        相关资源
        最近更新 更多