問題描述
我正在使用我網站前端的媒體庫,我想阻止使用者透過上傳無限數量的檔案來垃圾郵件。
因此,我想做一個或者以下全部:
-
為使用者提供最大上載能力; 即使用者最多可以上傳 10 兆位元組的檔案。
-
限制使用者可以在 per-post 上上傳的檔案數
-
限制使用者在點選”Insert” 按鈕時可以上傳的檔案數量,即 Flash 上傳者和經典上傳者只允許您一次上傳 2 個檔案。
這些都不是 bullet-proof,但他們希望使這樣的”spamming” 成為一個難題。
提前致謝,
最佳解決方案
假設您透過 WordPress 的本機功能,wp_handle_upload
或更多的 high-level 提供上傳功能,我們得出結論,幾個鉤子將被拉。
http://core.trac.wordpress.org/browser/tags/3.3/wp-admin/includes/file.php#L212
wp_handle_upload
函式可能是觸控該檔案的最後一個本機函式,並且將知道跟蹤所需的所有資訊。
這個功能裡面有兩個鉤子:wp_handle_upload 和 wp_handle_upload_prefilter 。後者首先,這可以檢查目前的限制,並阻止檔案上傳。前者將跟蹤檔案和計數。儲存資訊將由 update_user_meta 除外。
add_filter( 'wp_handle_upload', 'wpse47580_update_upload_stats' );
function wpse47580_update_upload_stats( $args ) {
$file = $args['file'];
$size = filesize( $file ); // bytes
$user_id = get_current_user_id();
$upload_count = get_user_meta( $user_id, 'upload_count', $single = true );
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', $single = true );
update_user_meta( $user_id, 'upload_count', $upload_count + 1 );
update_user_meta( $user_id, 'upload_bytes', $upload_bytes + $size );
}
add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );
function wpse47580_check_upload_limits( $file ) {
$user_id = get_current_user_id();
$upload_count = get_user_meta( $user_id, 'upload_count', $single = true );
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', $single = true );
$filesize = /* get filesize from $file array */;
$upload_bytes_limit_reached = apply_filters( 'wpse47580_upload_bytes_limit_reached', 1024*1024*10 ) > ( $filesize + $upload_bytes );
$upload_count_limit_reached = apply_filters( 'wpse47580_upload_count_limit_reached', 100 ) > ( $upload_count + 1 );
if ( $upload_count_limit_reached || $upload_bytes_limit_reached )
$file['error'] = 'Upload limit has been reached for this account!';
return $file;
}
理論上,這個工作; 實際上未經測試。讓我們知道怎麼回事。
每個帖子上傳限制將保留在後期元,可能就像 {$user_id}_upload_count
等。不明白為什麼不起作用。
如果您使用自定義程式碼來處理上傳 (我這樣做),那麼您可以像 wp_handle_uploads
那樣實現自己的操作和過濾器。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。