我知道这可能是有史以来最难做的编码之一,但我想尝试一下。
Im基本上是试图检测通过Wordpress media upload上传的所有(mp3)文件类型,并将其发送到异地,从而通过(ftp连接)将其上传到不同的服务器。
下面是我在数小时的研究后开始编写的代码,我觉得我有点受挫了,老实说,我甚至不知道我是否处于良好状态。我希望对Wordpress/PHP有更多了解的人能帮助我归档我正在做的事情。我这样做是为了避免主服务器因文件大小过大而过载,并将其限制为图像。
我希望上传到服务器B的结构是:serverB。com/music/Year/month/file。mp3
年份和月份应继承自wordpress发布日期(“Y/m”);
上传后,wordpress中出现的链接应该是serverB的链接。文件的com url。
非常感谢。以下是我启动的代码:
<?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