Sometimes getting 401 Invalid OAuth token, even after token refresh

Why is your refresh_token in $_POST?

Something seems very off with your code/work flow here. As the refresh token should be loaded from memory/database/storage not from $_POST

So not sure whats wrong here as yoru base work flow is wrong.

Also save yourself some hassle and use cURL instead of file_get_contents

I have a PHP user Auth example here