Chuck Aguilar Chuck Aguilar - 3 years ago 151
PHP Question

wp_remote_post not working and server returning 500

I'm trying to use

wp_remote_post
to register an user in an extern backend.

I have in my wordpress code:

$url = 'https://example.com/users/register/';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 60,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'email' => $email,
'name' => $name,
'last_name' => $last_name,
'password' => $password),
'cookies' => array()
)
);


But I'm getting a 500 error:


[raw] => HTTP/1.1 500 Internal Server Error
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 29 Sep 2017 17:31:14 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: close
X-Frame-Options: SAMEORIGIN


I don't know why. I tried the endpoint with postman, curl and an iOS App and it's working. So, I think the problem is somehow with Wordpress. Could it be that I'm making the request from a
http
and not
https
?

This is the nginx log:

46.101.102.90 - - [29/Sep/2017:17:31:14 +0000] "POST /users/register/ HTTP/1.1" 500 38 "https://example.com/users/register/" "WordPress/4.8.2; http://www.lifecompanion.eu"


so, the request is coming, but somehow it's not working (I already tried
'httpversion' => '1.1'
just in case, and got the same error though.

Maybe someone tried the same, or can tell me a best way to do it.

Answer Source

It seems that the problem is on the server side. If you try to send the data using application/x-www-form-urlencoded, it doesn't like it and returns the 500 status code. However, if it's multipart/form-data or application/json it works. You also don't need to specify the POST method when you're using wp_remote_post and setting the HTTP protocol to 1.0 has no affect.

You can try something like this:

$url = 'https://example.com/users/register/';
$response = wp_remote_post( $url, array(
    'timeout' => 60,
    'redirection' => 5,
    'blocking' => true,
    'headers' => array( 'Content-Type' => 'application/json' ),
    'body' => 
        json_encode( 
            array( 
                'email'     => $email,
                'name'      => $name,
                'last_name' => $last_name,
                'password'  => $password
            ) 
        ),
    'cookies' => array()                            
    )
);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download