Create post with REST API in php with file_get_contents

Actually I have no problems getting posts.
I need to create posts with the REST API in php with file_get_contents.

This is my code:

json_decode(
    file_get_contents(
        "http://my-site.com/wp-json/wp/v2/posts",
        false,
        stream_context_create(
            array(
                "http" => array(
                    "header"  => "Content-type: text/json\r\n",
                    "method"  => "POST",
                    "content" => json_encode(
                        array(
                            "slug" => "article-2",
                            "title" => "Article 2",
                            "content" => "Created with rest api",
                        )
                    )
                ),
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false
                )
            )
        )
    ),
    true
);

And I get this error: failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

So I tried having an auth with real wp username and password:

"http" => array(
    "header"  => "Content-type: text/json\r\n"."Authorization: Basic " . base64_encode("$username:$password"),
    "method"  => "POST",
    "content" => json_encode(
        array(
            "slug" => "article-2",
            "title" => "Article 2",
            "content" => "Created with rest api",
        )
    )
)

But same result.

How can I insert a post with the REST API from php using file_get_contents?

1 Answer
1

You’ll need to install a plugin to add authentication, by default it requires a cookie and a nonce token, but for CLI apps or PHP requests, you’ll want to install a basic auth plugin or use OAuth1/2

Leave a Comment