简体   繁体   中英

How to login a PHP script with another server via HTTP headers?

I'm trying to create a script that will login to an Icecast2 server and grab the metadata for the currently playing tracks. My issue is that the Icecast server is user/pass protected via basic HTTP login.

    <?php
        $fp = fsockopen("xxxxxxxx.com", 8000, $errno, $errstr, 30);
        if (!$fp) {
            echo "$errstr ($errno)<br />\n";
        } else {
            $out = "GET / HTTP/1.1\r\n";
            $out .= "Icy-MetaData:1\r\n";
            $out .= "Host: xxxxxxxx.com\r\n";
            $out .= "Connection: Close\r\n\r\n";

            fwrite($fp, $out);
            $arr = array();

            while (!feof($fp)) {
                $arr[] = fgets($fp, 128);
            }
            fclose($fp);
        }

        echo json_encode(trim(strip_tags($arr[73])));

?>

This is the script that has allowed me to grab metadata before the Icecast server was password protected.

In short, how do I send a user/pass via this script to the Icecast server to login and grab the info successfully? (Uses htpasswd)

Thanks in advanced!

Some research revealed this .

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt(CURLOPT_USERPWD, '[username]:[password]')

$data = curl_exec();
curl_close($ch);

However, it requires the usage of cURL instead of file sockets.

As described on Wikipedia , you need the Authorization: Basic header and base64_encode() username:password .

Code to add:

$out .= "Authorization: Basic " . base64_encode($user .":". $password);

Log in manually to check if the page uses cookies to authenticate users, if it does then you can use headers to send cookies, which should allow you to retrieve data from password protected pages.

$array = array(
      'http'=>array(
        'header'=>"Cookie: *cookiedatahere*"
      )
);

$context = stream_context_create($array);

$url = *password protected data source*;
$raw = file_get_contents($url, false, $context);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM