Make an HTTP POST request to upload a file in Wordpress - HTTP POST request get converted to GET

753 Views Asked by At

I want to have a HTTP POST link in my Wordpress website that lets another server to post an xml file every hour into the Wordpress server and I save it.

I created an index.php file in folders that map with the route I want, let say I need example.com/jobs/uploadFile, so I created a php file inside the folders /jobs/uploadFile of the root Wordpress directory.

<?php

if( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
  header($_SERVER["SERVER_PROTOCOL"]." Method Not Allowed", true, 405);
  exit;
}

$postData = trim(file_get_contents('php://input'));

$xml = simplexml_load_string($postData);

if($xml === false) {
    header($_SERVER["SERVER_PROTOCOL"]." Bad Request", true, 400);
    exit;
}

$xml->asXml('jobs.xml');
http_response_code(200);

1- I send a HTTP POST request via postman, but somehow the server or Wordpress changes it a HTTP GET request, so always the first if condition is executed. I'm using Laravel forge server with Nginx.

2- Appreciate any security advice about this approach, CORS...?

Thanks for your help

1

There are 1 best solutions below

0
On BEST ANSWER

Since it may help others, I answer my question. I was doing it the wrong way. The better way to do it is by using actions in a custom Wordpress plugin. Just create a custom plugin and use add_action inside it:

add_action( 'rest_api_init', function() {
    register_rest_route(
        'myapi/v1', 'myUploadURL',
        [
            'methods' => 'POST',
            'callback' => 'my_upload_function',
            'permission_callback' => '__return_true',
        ]
    );
});

And then you can get the $_FILES of the POST request in the my_upload_function() and save it on your server.