0

file_get_contents() 当我运行以下代码时,我正在尝试使用 PHP 函数连接到 McMyAdmin :

<?php
$url = 'http://mc.mywebsite.com/data.json?req=status';
$username = 'myuser';
$password = 'mypass';

$context = stream_context_create(array(
    'http' => array( 
      'method'  => 'POST', 
      'header'  => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)). 
                   "Content-type: application/x-www-form-urlencoded\r\n", 
      'timeout' => 3, 
    )
));
$data = file_get_contents($url, false, $context);
echo $data;
?>

我不断收到 401 错误。从我读过的内容来看,这应该通过身份验证。难道我做错了什么?

4

1 回答 1

1

改用 CURL:

<?php
    $Protocol = "http";
    $Server = "localhost:8080";
    $Username = "admin";
    $Password = "admin";

    //$Username:$Password@
    $fullURL = "$Protocol://$Server/data.json?" . $_SERVER['QUERY_STRING'];

    $curl_handle = curl_init();

    curl_setopt($curl_handle, CURLOPT_URL, $fullURL);
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_USERPWD, "$Username:$Password");
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array ("Accept: application/json"));

    $buffer = curl_exec($curl_handle);

    if ( $error = curl_error($curl_handle) ) 
    echo 'ERROR: ',"$error";

    curl_close($curl_handle);

    $Response = $buffer;

    header('Content-Type: application/json');
    echo $Response;
?>

请注意,如果没有“Accept: application/json”标头 - McMyAdmin 2 将拒绝 API 请求。

于 2012-02-06T02:07:02.393 回答