CURLOPT_USERPWD与stream_context_create的等效实现及相关疑问
Absolutely, you can achieve the exact same effect as CURLOPT_USERPWD when using stream_context_create()—and your code is perfectly correct for this purpose. Let’s break this down clearly:
Why your implementation works
CURLOPT_USERPWD in cURL is just a convenience feature that automatically builds the required HTTP authentication header for you. Under the hood, it takes your username:password string, runs it through base64_encode(), and formats it into the Authorization: Basic header.
Your manual code does exactly that same work explicitly, so it’s a 1:1 equivalent. When you pass this context to stream-based functions like file_get_contents(), the server will receive the identical authentication header it would get from a cURL request using CURLOPT_USERPWD.
Is base64_encode() mandatory?
Yes, it’s required. HTTP Basic Authentication (defined in RFC 7617) specifies that the username:password pair must be encoded as a Base64 string. This ensures the credentials are transmitted as safe ASCII characters, avoiding formatting issues with special symbols like colons, spaces, or non-ASCII characters that could break HTTP header parsing.
Skipping the Base64 encoding will result in an invalid Authorization header, and the server will reject your authentication attempt.
Quick edge case note
If your username or password contains a colon (:), don’t worry—Base64 encoding handles this correctly. Servers split the decoded string on the first colon to separate the username and password, so even passwords with colons will be parsed properly.
内容的提问来源于stack exchange,提问作者JackSmith

