让代码更简单

WordPress上传图像函数media_handle_upload详解

重要:本文最后更新于2020-05-15 08:25:52,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗

最近几篇文章好像涉及到wordpress文件上传的功能,为了方便大家学习wordpress,以及对大家的网站安全考虑,在此介绍下wordpress官方提供的媒体上传函数media_handle_upload。使用它你不必考虑像PHP的文件上传函数那样是否会存在传马漏洞,wordpress的开发者已经帮你写好了验证,下面一起来学习下吧。

函数介绍

复制
media_handle_upload( string $file_idint $post_idarray $post_data = array(),array $overrides = array('test_form' => false) )

保存post上传的文件,并绑定一篇文章。

原型

函数位于wp-admin/includes/media.php文件中,在线地址:

复制
https://developer.wordpress.org/reference/files/wp-admin/includes/media.php/

参数

  • $file_id
    (string(必须) 文件发送的 $_FILES 数组的索引。
  • $post_id
    (int(必须) 要将媒体项目附加到的帖子的POST ID。必需的,但可以设置为0,创建与POST无关的媒体项。
  • $post_data
    (array(可选) 覆盖一些附件。
    默认值: array()
  • $overrides
    (array(可选) 重写函数 wp_handle_upload()
    默认值: array(‘test_form’ => false)

 

返回值

(int|WP_Error) 成功返回附件ID,失败返回wp_error错误对象。

使用示例

从网站前端的表单上传附件。上传表单可能如下所示:

复制
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>

PHP保存文件代码:

复制
<?php

// Check that the nonce is valid, and the user can edit this post.
if ( 
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] ) 
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// The nonce was valid and the user has the capabilities, it is safe to continue.

// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );

// Let WordPress handle the upload.
// Remember, 'my_image_upload' is the name of our file input in our form above.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );

if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}

} else {

// The security check failed, maybe show the user an error.
}

感觉很棒!可以赞赏支持我哟~

4 打赏

评论 (0)

登录后评论
QQ咨询 邮件咨询 狗哥推荐