0

I am working on a custom endpoint to handle ajax media uploads with media_handle_upload().

I have created a custom endpoint with a route that is tested and works, however when I try require the necessary files so that I can use media_handle_upload(), it returns a 500 internal server error with each request but still uploads the media correctly in to the media library.

I have tried to figure this out for a while now but I dont understand why it's happening.

Hoping somebody here can point me in the right direction!

To clearify, everything works as expected, the internal server error does not hinder the upload to happen correctly, but the error occurs with every request, no matter what.

Here is the function to upload: (path to custom routes file = /inc/custom-routes/custom-route.php)

function uploadFileFE ($data) {

              if ( isset( $_FILES["file"] ) ) {

                require ABSPATH . 'wp-admin/includes/image.php';
                require ABSPATH . 'wp-admin/includes/file.php';
                require ABSPATH . 'wp-admin/includes/media.php';

                  $attachment_id = media_handle_upload( 'file', 0 );

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

              } else {

                  echo "The empty check failed! Something went horribly wrong!";
              }

             wp_die();

          }

Update (with working code, adjusted from answer below)

So, the answer that Sally CJ gave was correct, I'm updating with the new code so that if anyone else does the same mistake I did, they'll see the complete working code.

function uploadFileFE ($data) {

          if ( isset( $_FILES["file"] ) ) {

            //$glSiteUrl = get_site_url();

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

              $attachment_id = media_handle_upload( 'file', 0 );

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

          } else {

              return "The empty check failed! Something went horribly wrong!";
          }

        }
  • What's your register_rest_route() code? Is the uploadFileFE the endpoint callback? But even if not, you shouldn't call wp_die() or do echo there. – Sally CJ Apr 26 at 3:30
  • The route works fine. Yes, uploadFileFE is the callback. It's only when i require the files you see required in the function that things get messy. And I don't understand why. If i remove the require files, I get no error other than the undefined function of wp_handle_upload ofc, since it's dependencies is lacking without those files. – Steve Rodgers Apr 26 at 3:40
  • 1
    My answer might help? And in your code, you might want to use require_once instead of require... just in case. – Sally CJ Apr 26 at 4:50
  • Does the code definitely not work if you don't include the files? Have you confirmed that they need to be included? – Jacob Peattie Apr 26 at 7:51
  • @JacobPeattie The code does not work if the files are not included, no. – Steve Rodgers Apr 26 at 12:24
0

From the wp_die() reference,

$args
(string|array|int) (Optional) Arguments to control behavior. If $args is an integer, then it is treated as the response code.

'response' (int) The HTTP response code. Default 200 for Ajax requests, 500 otherwise.

So your REST API endpoint returns the error 500 because that's the default header status sent by the wp_die function.

And I recommend you to return a proper value — e.g. a WP_Error instance on error, or a WP_REST_Response instance on success. Try these variations and compare the responses:

Option 1

// Works, but with a 500 status code.
function uploadFileFE() {
    wp_die();
}

Option 2

// Works, but shouldn't be used unless the client is *not* expecting a JSON response.
function uploadFileFE() {
    echo 'foo';
}

Option 3

// I'd use this. WordPress will apply rest_ensure_response() to the returned value.
function uploadFileFE() {
    return 'foo';
    //return WP_REST_Response( 'foo' ); // or use this, or below to send an error..
    //return new WP_Error( 'invalid_file', 'Invalid file!', array( 'status' => 400 ) );
}
  • Yes, that was the issue. The wp_die() function messed it up. Now it works perfectly! – Steve Rodgers Apr 26 at 12:35
  • :) I actually did test the function with just the require lines without the wp_die();, and confirmed the issue was the wp_die();. – Sally CJ Apr 26 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.