doujiejujixi27244 2015-04-09 06:59
浏览 70
已采纳

执行cURL请求时出错

This code always returns user doesn't exist from the API:

$data2 = array('user'=>$vars['mcusername'],
              'pwd'=>$vars['mcpassword'],
              'group'=>$postfields['group'],
              'action'=>'Save');    

// Connect to dvb API
$configWebAddress = "http://192.168.0.12:4040/dvbapi.html?part=userconfig&";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $configWebAddress);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
$data = curl_exec($ch);
curl_close($ch);

The string that works in a browser is this:

dvbapi.html?part=userconfig&user=PeterTest&pwd=obfuscated&group=1,2&disabled=0&action=Save
  • 写回答

1条回答 默认 最新

  • douyanqu9722 2015-04-09 08:02
    关注

    When you access the URL in the browser, you're performing a GET. In your cURL attempt, you're attempting to POST. This is likely the issue; the script may only accept GET.

    Try using this cURL code instead:

    // Gather up all the values to send to the script
    $data2 = array('part'   => 'userconfig',
                   'user'   => $vars['mcusername'],
                   'pwd'    => $vars['mcpassword'],
                   'group'  => $postfields['group'],
                   'action' => 'Save');  
    
    // Generate the request URL
    $configWebAddress = "http://192.168.0.12:4040/dvbapi.html?".http_build_query($data2);
    
    // cURL the URL for a responce
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $configWebAddress);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    
    // Show the responce
    var_dump($data);
    

    You can use http_build_query() to turn your array into a URL-encoded string to make the GET request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?