How to upload an image to WordPress Database from a mobile app? - Code on a laptop screen
How to upload an image to WordPress Database from a mobile app? - Photo by Luca Bravo on Unsplash

How to upload image to WordPress Database from mobile app?

This article will help to understand How to upload image to WordPress Database from mobile app?, along with a fully working code (a function to upload an image to WP Database)

upload image to WordPress Database from mobile app
How to upload image to WordPress Database from mobile app? – Photo by Rodrigo Bacellar on Unsplash

If you are developing a mobile App using WordPress as a backend then you need to make use of WP Rest API.

The WP REST API provides API endpoints for WordPress data types that allow developers to interact with sites remotely by sending and receiving JSON (JavaScript Object Notation) objects.

REST API Handbook by WordPress

How to upload image to WordPress Database from mobile app?

media_handle_upload( ‘image’, 0 );

https://codex.wordpress.org/Function_Reference/media_handle_upload

‘image’ – It has all image data to be uploaded which comes from the $_FILES request

0 – set the second argument to zero so that the image is not associated or assigned to any post instead the image will be independently saved to the database.

Few dependencies need to be included above this function to work

  • require_once( ABSPATH . ‘wp-admin/includes/image.php’ );
  • require_once( ABSPATH . ‘wp-admin/includes/file.php’ );
  • require_once( ABSPATH . ‘wp-admin/includes/media.php’ );

Check under Examples on https://codex.wordpress.org/Function_Reference/media_handle_upload For proper use of it.

Technically there is no difference at all if you need to upload an image coming via a Form on the mobile app or from simple web app front end Form, in both the case image upload is taken care the same way on the PHP side.

Full working code (function) to update user profile with profile picture & other user details like ‘first_name’, ‘last_name’ ,’company’, ‘job_title’, ‘interest’,’linkedin’, ‘twitter’, ‘facebook’

// update user profile with profile picture & other user details like
// 'first_name', 'last_name' ,'company', 'job_title', 
// 'interest','linkedin', 'twitter', 'facebook'

public function update_user_profile( WP_REST_Request $request ) {

       // default response to send if no other response is generated.
        $response = array(
                          'Status' => 2, 
                          'Response' => array(), 
                          'Error' => 'Nothing To Process'
                         );

        // We are using JSON Web Token (JWT) - 
        // The reason why JWT is used is to prove 
        // that the sent data was 
        // actually created by an authentic source.
        // get authorization code send in header

        $access_token = $request->get_header( 'Authorization' );
        if( empty($access_token) || 
          ( isset($access_token) && 
            !$this->verify_token($access_token)) ) {

            $response = array('Status' => 2,                 
            'Response' => array(), 
            'Error' => 'cant verify access token');

            wp_send_json($response);
        }

   // $this->email - it is set when $this->verify_token is called
   $wp_user_obj = get_user_by('email', $this->email);

   // get user id from the user object
   $userid = $wp_user_obj->data->ID;

    // Retrieves merged parameters from the request.
    $user_fields = $request->get_params();

    // update user meta values for the user id
    foreach( $user_fields as $user_field => $value ) { 

     $status[$user_field] = update_user_meta(
                                              $userid, 
                                              $user_field, 
                                              $value
                                             );
     }

        $error = '';
  // Retrieves multipart file parameters from the body.        
  $profile_picture = $request->get_file_params( 'profile_picture' );        

  // upload profile picture
  if( !empty($profile_picture) ) {

   if ( ! function_exists( 'media_handle_upload' ) ) {

   // 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' );
  }

  $attachment_id = media_handle_upload( 'profile_picture', 0 );                                        
  if ( is_wp_error( $attachment_id ) ) {
  
      // There was an error uploading the image.
      if( $attachment_id->errors['upload_error'][0] ) {
        $error = $attachment_id->errors['upload_error'][0];
      } else {
        $error = 'Failed to upload to Profile Picture';
      }

  } else {

   // The image was uploaded successfully!
     $profile_picture_url = wp_get_attachment_url( $attachment_id );
     $status['profile_picture'] = update_user_meta(  
                                              $userid, 
                                              'profile_picture', 
                                              $profile_picture_url 
                                            );
     }
 }
        
 $response = array(
                   'Status' => 1, 
                   'Response' => $status, 
                   'Error' => ''
                  );

  if ( !empty($error) ) {
        $response['Status'] = 3;
        $response['Error']  = $error;
     }

   wp_send_json($response);                
}

Was that a useful Article? Let me know your comments & feedback.

Another Important read from Rohutech:

About the author

Rohan Kamble

A Web Developer by profession, who loves the web to the core with over 9 Years of Experience working on a wide range of domains like websites on e-commerce, Travel, Alumni, matrimonial, company's professional sites, Finance, company internal communications and many more. Also WordPress Plugins & Chrome extensions.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.