2014-11-06 41 views
-1

我该如何在PHP中使用curl来执行下面的代码?我该如何使用curl来代替fopen

因为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 

回答

0

简单的HTTP请求卷曲:

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; 
+0

其中发布数据? – 2014-11-06 07:16:09

+0

@RakeshSharma检查 – 2014-11-06 07:19:17

+0

Bravo CS GO。它运作良好! – Burhan 2014-11-06 07:56:21

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; 
}