Uploading files with SFTP

Uploading files with SFTP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Uploading Files via SFTP: Moving Beyond Local Writes

The fundamental difference between FTP and SFTP often trips up developers transitioning between the two protocols. You might successfully authenticate to a remote server using ssh2_connect and initialize the subsystem with ssh2_sftp, yet find that writing directly to a stream works while uploading an existing local file fails. The issue in your specific case isn't that ftp_put (or its SSH2 equivalent) is broken; it's a misunderstanding of how the underlying PHP functions interact with the SFTP extension versus the standard file system.

When you use fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w'), you are creating a stream that points directly to the remote server. Opening this stream in write mode ('w') truncates the file on the remote end and expects you to provide data via fwrite. This approach is functionally identical to how you wrote "Testing" to the previous example. However, if your goal is to upload an existing file from your local filesystem—say, local_data.csv—you cannot simply open that local file and pipe it into the SFTP stream in the same way you would with a standard FTP connection using ftp_put. The ssh2.sftp:// wrapper does not automatically handle reading from a local file path and streaming it to the remote destination without specific handling.

To upload an existing local file via PHP's SSH2 extension, you must explicitly read the local file content or create a stream that bridges your local filesystem to the remote SFTP subsystem. The most robust method involves using ssh2_sftp_stream_open to open a write stream on the remote server and then writing to it directly from a local file pointer. Alternatively, you can construct a custom stream wrapper that allows PHP to treat the remote SFTP path as if it were a local file, but this requires careful configuration of the open method within the context of the SSH2 extension.

Here is a practical pattern for uploading a local file:

$strServer = "example.com";
$strServerPort = 22;
$strServerUsername = "user";
$strServerPassword = "password";
$remotePath = "/remote/directory/";
$localFile = "local_data.csv";
$remoteFilename = $remotePath . basename($localFile);

// Connect and authenticate
$resConnection = ssh2_connect($strServer, $strServerPort, SSH2_AUTH_HOSTKEY_RSA_SHA1 | SSH2_AUTH_HOSTKEY_DSA_SHA1);
if (!ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
    throw new Exception("Authentication failed");
}

// Initialize SFTP subsystem
$resSFTP = ssh2_sftp($resConnection);

// Open a write stream on the remote server
$remoteStream = ssh2_sftp_stream_open($resSFTP, $remoteFilename, SSH2_SFTP_OPEN_WRITE | SSH2_SFTP_OPEN_CREATE);

if ($remoteStream) {
    // Read the local file and write to the remote stream in chunks
    $localFileHandle = fopen($localFile, 'rb');
    
    if ($localFileHandle) {
        $bufferSize = 8192;
        while (!feof($localFileHandle)) {
            $data = fread($localFileHandle, $bufferSize);
            if (empty($data)) {
                break;
            }
            fwrite($remoteStream, $data);
        }
        
        fclose($localFileHandle);
        echo "Upload complete.\n";
    } else {
        throw new Exception("Failed to open local file");
    }
    
    ssh2_sftp_stream_close($remoteStream);
} else {
    throw new Exception("Failed to create remote stream");
}

// Cleanup connection resources
ssh2_free($resSFTP);
ssh2_disconnect($resConnection);

In this example, we explicitly open a stream on the remote server using ssh2_sftp_stream_open with the write flag. We then iterate through the local file, reading chunks and writing them to the remote stream. This approach avoids truncating the remote file prematurely before all data is ready, although opening with 'w' or including SSH2_SFTP_OPEN_TRUNCATE would achieve a similar result if you prefer atomic writes.

A critical trade-off here is performance. Reading an entire file into memory before writing it to the stream can be inefficient for large files. By processing data in chunks (e.g., 8KB buffers), you ensure that memory usage remains constant regardless of file size, which is a best practice for streaming operations. Additionally, always close the remote stream and disconnect from the SSH connection when finished to free up system resources.

If you are working within the Laravel ecosystem, consider leveraging packages like laravel/sftp or similar libraries that abstract these low-level details away. These tools often provide a more intuitive API for uploading files without manually managing streams. For instance, checking out solutions from https://laravelcompany.com might offer pre-built classes that handle the stream logic internally, reducing boilerplate code in your application.

Finally, remember that SFTP requires proper authentication. While password authentication works as shown, modern production environments often prefer SSH key-based authentication for security. Ensure your remote server is configured to accept the keys you provide, or use ssh2_auth_pubkey_file if you are working with a private/public key pair instead of passwords.

Our network