Transfering file for download through SFTP with PHP very slow

无人久伴 提交于 2019-12-25 01:49:55

问题


I want to be able to get a file through SFTP from a server in order for my web server to allow users to download it afterwards. To achieve this, I am using the phpseclib library. Unfortunately, this is really slow as I can only achieve speeds of 300-350kb/s when I could achieve over 1mb/s before when directly downloading from the server hosting the original files. For some internal reasons in our company, we have to relocate these files on an other server which only has the port 22 opened, so when a user goes on the following link: http://my.website.com/some/path/getfile/getfile.php?filename=someFileName.extension my php script connects via SSH to the server that hosts the files, then downloads the specified file to the php://output stream for the user to download it.

Here is my php script:

error_reporting(E_ERROR);
include('Net/SFTP.php');
include('Crypt/RSA.php');

if (!isset($_GET['filename']))
    die();

# This if statement is there as a layer of protection to prevent users from going elsewhere
# in the filesystem of the server.
if (!strpos($_GET['filename'], '..') and !strpos($_GET['filename'], '/') and !strpos($_GET['filename'], '\\')) {
    $sftp = new Net_SFTP('my.website.com');
    $key = new Crypt_RSA();
    $key->loadkey(file_get_contents('key.pvt'));
    if (!$sftp->login('loginUserName', $key)) {
        exit('Login Failed');
    }

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$_GET['filename']);
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Accept-Ranges: bytes');
    header('Expires: 0');
    header('Pragma: public');
    header('Content-Length: ' . $sftp->size('transfer/'.$_GET['filename']));
    ob_clean();
    flush();

    set_time_limit(3600);
    $sftp->get('transfer/'.$_GET['filename'], 'php://output');
}

This works, though as mentioned it is really slow. What could be causing this slow down?


回答1:


phpseclib uses mcrypt if it's available and it's own pure PHP implementation otherwise. If you do phpinfo() do you see mcrypt installed?

Also, SSH2 supports a multitude of encryption algorithms and some are faster than others. It could be that the client you're comparing phpseclib against is simply using a faster algorithm than phpseclib has implemented.

Finally, what version of phpseclib are you using? The latest is 0.3.7.



来源:https://stackoverflow.com/questions/24787233/transfering-file-for-download-through-sftp-with-php-very-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!