Skip to content

Instantly share code, notes, and snippets.

@asfo
Created September 6, 2023 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asfo/e2b55f4e6963f98ebe816c6f6b1cbf45 to your computer and use it in GitHub Desktop.
Save asfo/e2b55f4e6963f98ebe816c6f6b1cbf45 to your computer and use it in GitHub Desktop.
Send WP Media to Another Server Using FTP
<?php
// Not working at the moment as this cause an issue with Elementor
function upload_to_ftp( $args ) {
$upload_dir = wp_upload_dir();
$upload_url = get_option('upload_url_path');
$upload_yrm = get_option('uploads_use_yearmonth_folders');
$settings = array(
'host' => '', // * the ftp-server hostname
'port' => 21, // * the ftp-server port (of type int)
'user' => '', // * ftp-user
'pass' => '', // * ftp-password
'cdn' => '', // * This have to be a pointed domain or subdomain to the root of the uploads
'path' => '', // - ftp-path, default is root (/). Change here and add the dir on the ftp-server,
'base' => $upload_dir['basedir'] // Basedir on local
);
if( empty( $upload_url ) ) {
update_option( 'upload_url_path', esc_url( $settings['cdn'] ) );
}
$connection = ftp_connect( $settings['host'], $settings['port'] );
$login = ftp_login( $connection, $settings['user'], $settings['pass'] );
if ( !$connection || !$login ) {
die('Connection attempt failed, Check your settings');
}
function ftp_putAll($conn_id, $src_dir, $dst_dir, $created) {
$d = dir($src_dir);
while($file = $d->read()) { // do this for each file in the directory
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
}
$created = ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file, $created); // recursive part
} else {
$upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
if($upload)
$created[] = $src_dir."/".$file;
}
}
}
$d->close();
return $created;
}
$delete = ftp_putAll($connection, $settings['base'], $settings['path'], array());
foreach ( $delete as $file ) {
unlink( $file );
}
return $args;
}
add_filter( 'wp_generate_attachment_metadata', 'upload_to_ftp' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment