2012-02-06 26 views
0

我試圖使用PHP函數file_get_contents() 當我運行下面的代碼連接到McMyAdmin:連接到McMyAdmin與PHP的file_get_contents()

<?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錯誤。從我讀過的這個應該可以通過認證。難道我做錯了什麼?

回答

1

使用捲曲,而不是:

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

    //$Username:[email protected] 
    $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; 
?> 

注意,如果沒有 「接受:應用/ JSON的」 頭 - McMyAdmin 2將拒絕API請求。

+0

謝謝,在對代碼進行了一些小的修改以適合我的特定McMyAdmin配置後,它完美地工作 – DontTurnAround 2012-02-06 02:21:47