Author - StudySection Post Views - 2,751 views
server

Upload Files to a Server using SFTP in PHP

FTP is the traditional file transfer protocol used to transfer files over the internet. Similarly, SFTP is also a file transfer protocol that allows you to transfer files but adds security to the process. SFTP uses SSH encryption to protect the data while transferring the file, so the data is not exposed to outside entities.

In this post, I have explained how to transfer a file using SFTP credentials in PHP. This is the basic example which can be used in any PHP framework.

Below is the code example to upload the file to the server using the SFTP.
try {
$dataFile = 'filename';
$sftpServer = "your SFTP hostname ";
$sftpUsername = "your SFTP username";
$sftpPassword ="your SFTP password";
$sftpPort = "your SFTP port";
$sftpRemoteDir ="your SFTP directory to upload the file into";
$ch = curl_init('sftp://' . $sftpServer . ':' . $sftpPort . $sftpRemoteDir . '/' . basename($dataFile));
$fh = fopen('path of the local file/'.$dataFile, 'r');
if ($fh) {
curl_setopt($ch, CURLOPT_USERPWD, $sftpUsername . ':' . $sftpPassword);
curl_setopt($ch, CURLOPT_UPLOAD, true);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($ch, CURLOPT_INFILE, $fh);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('path of the local file/'.$dataFile));
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($response) {
echo "Success";
} else {
echo "Failure";
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n" . $verboseLog . "\n";
}
}
} catch (Exception $e) {
log_message("info", "Exception in uploading file to ftp---" . print_r($e->getMessage(), 1));
echo "error exception".$e->getMessage();
}

After running the above code your file will be in the destination folder.

If you need to prove your skills in the .NET framework, get .NET certified on StudySection. StudySection provides .NET certification exam for beginners as well as experts in the .NET framework. This .NET certification can improve your resume’s success rate.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri