OXY NOTES

wp_remote_get()でAuthentication required!が出る場合の対処法

答えは単純、ベーシック認証が必要

PHPで何かファイルを取得する場合、file_get_contents()を利用することが多いと思います。
ただWordPressの場合はwp_remote_get()の利用が推奨されています。

推奨ならそっちを利用しようかな」とプラグインの開発中にローカルサイトでテストしたところ、以下の表示が出て困りました。

Authentication required!

This server could not verify that you are authorized to access the URL "取得するファイル". You either supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.

In case you are allowed to request the document, please check your user-id and password and try again.

If you think this is a server error, please contact the webmaster.

Error 401

wp_remote_get()はリモートからのアクセスを想定しているため、同一サイト内であってもベーシック認証が必要になるようです。

Authentication required!が出た際の解決法

以下のようにwp_remote_get()の第二引数にオプションを指定します。

// ベーシック認証解除用(hogeにユーザー名、hugaにパスワードを設定する)
$args = array(
	'headers' => array(
		'Authorization' => 'Basic ' . base64_encode( hoge . ':' . huga )
	)
);

$buff = wp_remote_get( $filename, $args );

コメントにある通り、hogeの部分にユーザー名、hugaの部分にパスワードを入れてください。
これで問題は解決します。
(ただしプラグイン等ではパスワードがバレルので本番環境では使えませんね)