我怎么能用curl而不是fopen

时间:2014-11-06 07:11:16

标签: php curl fopen wiziq

如何使用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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
}
相关问题