I'm aware this might be some of the hardest coding to do ever, but thought of giving it a try.
Im basically trying to detect all (mp3) filetypes uploaded through the Wordpress media upload and send them offsite, thus have them uploaded to a different server through (ftp connection).
Below is the code i started after hours of research and i think i'm stucked, honestly i don't even know if i'm at a good point. I hope someone who has much more knowledge with Wordpress/PHP can help me archive what i'm trying to do. I'm doing this to save the main server from been overloaded with big file sizes and limit it to images.
I would want the structure uploaded to Server B is: serverB.com/music/Year/month/file.mp3
The year and month should inherit from wordpress post date( 'Y/m' );
After it is uploaded the link that appears in wordpress should be that of serverB.com url to the file.
Thank you. Below is the code i started:
<?php
/*
* Change upload directory/server for mp3 files
* Only works in WordPress 3.3+
*/
add_filter('wp_handle_upload_prefilter', 'music_pre_upload');
add_filter('wp_handle_upload', 'music_post_upload');
function music_pre_upload($file){
add_filter('upload_dir', 'music_remote_upload_dir');
return $file;
}
function music_post_upload($fileinfo){
remove_filter('upload_dir', 'music_remote_upload_dir');
return $fileinfo;
}
function music_remote_upload_dir($path){
$extension = substr(strrchr($_POST['name'],'.'),1);
if(!empty($path['error']) || $extension != 'mp3') { return $path; } // if other filetype send to default uploads folder.
/**
* Change this to match your server
* You only need to change the those with (*)
* If marked with (-) its optional
*/
$post_date = '/' . date( 'Y/m' );
$settings = array(
'host' => 'host or IP', // * the ftp-server hostname
'user' => 'ftp-username', // * ftp-user
'pass' => 'ftp-pass', // * ftp-password
'cdn' => 'external-server.com', // * This have to be a pointed domain or subdomain to the root of the uploads
'path' => '/music', // - ftp-path, default is root (/). Change here and add the dir on the ftp-server
'date' => $post_date // Local post date
);
/**
* Host-connection
* Read about it here: http://php.net/manual/en/function.ftp-connect.php
*/
if(function_exists('ftp_ssl_connect'))
{
$connection = ftp_ssl_connect( $settings['host'] );
}
else
{
$connection = ftp_connect( $settings['host'] );
}
/**
* Login to ftp
* Read about it here: http://php.net/manual/en/function.ftp-login.php
*/
$login = ftp_login( $connection, $settings['user'], $settings['pass'] );
/**
* Check ftp-connection
*/
if ( !$connection || !$login ) {
die('Connection attempt failed, Check your settings');
}
ftp_pasv($resource, true); // To avoid rectify warning
if( ftp_put( $connection, $settings['path'] . "/" . $settings['date'] . "/" . $file, FTP_BINARY ) ) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
} // End function