-1

我如何在 php 中使用 curl 执行下面的代码?

因为 fopen 在服务器端有问题。这个示例代码片段是关于 wizIQ API 的使用...

class HttpRequest
{
        function wiziq_do_post_request($url, $data, $optional_headers = null)
          {  
            $params = array('http' => array(
                          'method' => 'POST',
                          'content' => $data
                       ));


            if ($optional_headers !== null) 
            {

                $params['http']['header'] = $optional_headers;

            }
            $ctx = stream_context_create($params);






            $fp = fopen($url, 'r+',false, $ctx);
            if (!$fp) 
            {
                throw new Exception("Problem with $url, $php_errormsg");
            }
            $response = @stream_get_contents($fp);
            if ($response === false) 
            {
                throw new Exception("Problem reading data from $url, $php_errormsg");
            }

             return $response;
          }
}//end class HttpRequest
4

2 回答 2

0

尝试

// making array to query string like id=fhg&name=df
foreach($data as $key => $val){
  $str.= $key.'='.$val.'&';
}
rtrim($str,'&');
$url = 'your url';
$result = curl($url, $str);
print_r($result);
function curl($url,$data) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  // add your header if require
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
  $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}
于 2014-11-06T07:18:42.803 回答
0

简单的 HTTP CURL 请求:

function get_response( $url, $post_params )
{
    $channel = curl_init();
    curl_setopt($channel, CURLOPT_URL, $url);
    curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($channel, CURLOPT_TIMEOUT, 5);
    curl_setopt($channel, CURLOPT_ENCODING, "gzip");
    curl_setopt($channel, CURLOPT_VERBOSE, true);
    curl_setopt($channel, CURLOPT_POST, true);          //set POST request to TRUE
    curl_setopt($channel, CURLOPT_POSTFIELDS, $post_params);  //set post params
    curl_setopt($channel, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201');
    curl_setopt($channel, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($channel, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    $output = curl_exec($channel);

    curl_close( $channel );
    return $output;
}

$url = "http://www.stackoverflow.com";
$post_params = "YOUR_FIELDS";
$response = get_response($url, $post_params);
echo $response;
于 2014-11-06T07:14:40.063 回答