Skip to content

Instantly share code, notes, and snippets.

@kalmanolah
Created April 16, 2014 07:41
Show Gist options
  • Save kalmanolah/10825841 to your computer and use it in GitHub Desktop.
Save kalmanolah/10825841 to your computer and use it in GitHub Desktop.
Real ugly PHP function for uploading file contents via FTP or SFTP
<?php
function uploadFileContentsViaFtp(
$sftp = false,
$host,
$port,
$user,
$password,
$folder,
$file_name,
$file_contents
) {
// Create a temporary file to store our content in
$temp = tmpfile();
fwrite($temp, $file_contents);
rewind($temp);
// Set up the target resource
$resource = null;
if ($sftp) {
$resource = @ssh2_connect($host, $port);
if (!$resource) {
return false;
}
$auth_success = @ssh2_auth_password($resource, $user, $password);
if (!$auth_success) {
return false;
}
$resource = @ssh2_sftp($resource);
if (!$resource) {
return false;
}
} else {
$resource = "${user}:${password}@${host}:${port}";
}
// Create the full path to the target file
$path = ($sftp ? ssh2_sftp_realpath($resource, '.') : '') . '/' . ($folder ? $folder : '') . $file_name;
$type = $sftp ? 'ssh2.sftp' : 'ftp';
$full_path = "${type}://${resource}${path}";
// Create the correct stream context
$stream_options = array();
if (!$sftp) {
$stream_options['ftp'] = array('overwrite' => true);
}
$stream_context = stream_context_create($stream_options);
// Open target file
$target = @fopen($full_path, 'w', 0, $stream_context);
// We've failed if we couldn't open the target file for writing
if (!$target) {
return false;
}
// Copy source stream to target stream
stream_copy_to_stream($temp, $target);
// Close open file handles, deleting the temporary file in the process
fclose($target);
fclose($temp);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment