Search code examples
phpcurlsftp

PHP CURL SFTP Read File?


I am trying to figure out how to read a file and get the contents from a remote SFTP connection via php/curl. I currently have the code below to read a list of files in a directory.

$ch = curl_init('sftp://' . $sftpServer . ':' . $sftpPort . $sftpRemoteDir . '/');
curl_setopt($ch, CURLOPT_USERPWD, '*****:*****');
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($ch, CURLOPT_DIRLISTONLY, '1L');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch); 
$error = curl_error($ch);
curl_close($ch);

if I change curl_init to the line below (file name added) how can I read that file?

$ch = curl_init('sftp://' . $sftpServer . ':' . $sftpPort . $sftpRemoteDir . '/filename.txt');

Solution

  • The $response variable will contain the file data. If you want to save the file to your server's machine, you can write the contents of that file using file_put_contents.

    $ch = curl_init('sftp://' . $sftpServer . ':' . $sftpPort . $sftpRemoteDir . '/filename.txt');
    curl_setopt($ch, CURLOPT_USERPWD, '*****:*****');
    curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
    curl_setopt($ch, CURLOPT_DIRLISTONLY, '1L');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch); 
    $error = curl_error($ch);
    curl_close($ch);
    
    file_put_contents("/path/to/save/filename.txt", $response);
    

    If you want to read the plaintext (available for text files, including .txts), then you should be able to simply read the $response variable, which should be a string.