-1

I have created the following PHP code long time ago and it works, but I don't understand, why base64_encode is working with 2 variables, which are put together, inside a string base64_encode("$user:$pass")?

I hope somebody can help me to understand it.

Here the complete code section:

    $user  = "username";
    $pass= "password";

    //HTTP options
    $opts = array('http' =>
        array(
            'method'    => 'GET',
            'header'    => array ('Authorization: Basic '.base64_encode("$user:$pass"))
        )
    );

    //Do request
    $context = stream_context_create($opts); // creates GET request with encoded password 
    $url = "http://www.myURL.com/subpage";
    $list = file_get_contents($url, false, $context); // get xml info
1
  • "$user:$pass" is the same as $user . ':' . $pass. Commented Jun 9, 2022 at 9:01

1 Answer 1

1

You're not passing 2 variables into the base64 function.

The two variables are contained within a single static string. When the code runs, the variables are interpolated to their real values to form the completed string, and then after that it's passed into the function.

If it helps to break it down, the code is equivalent to:

$credentials = "$user:$pass";
base64_encode($credentials);

which is equivalent to

$credentials = $user.":".$pass;
base64_encode($credentials);

PHP string interpolation syntax might be helpful background reading.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.