我使用以下代码,但出于安全原因,我的服务器allow_url_fopen
已关闭。如何使用curl。
$request = array(
'method' => $method,
'params' => $params,
'id' => $currentId
);
$request = json_encode($request);
$this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";
// performs the HTTP POST
$opts = array ('http' => array (
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $request
));
$context = stream_context_create($opts);
if ($fp = fopen($this->url, 'r', false, $context)) {
$response = '';
while($row = fgets($fp)) {
$response.= trim($row)."\n";
}
$this->debug && $this->debug.='***** Server response *****'."\n".$response.'***** End of server response *****'."\n";
$response = json_decode($response,true);
} else {
throw new Exception('Unable to connect to '.$this->url);
}
答案 0 :(得分:0)
我为此目的编写的函数可能会对您有所帮助。但要小心,因为它没有根据您的具体用例进行调整。
<?php
/**
* @param $base First part of the URL to direct the request to
* @param $path Second part of the URL
* @param $param Array of parameters to be used for the request
* @return The result of the request if successful otherwise false
*/
function request($base = "", $path = "", $param = array()) {
$ch = curl_init();
$url = $base . $path;
if (isset($param["get"])) {
$getparams = implode("&", $param["get"]);
$url .= "?" . $getparams;
}
if (isset($param["post"])) {
$postparams = implode("&", $param["post"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postparams);
}
if (isset($param["header"])) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $param["header"]);
}
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$result = request("http://www.iana.org/domains/example/");
var_dump($result);
?>
答案 1 :(得分:0)
$request = array(
'method' => $method,
'params' => $params,
'id' => $currentId
);
$request = json_encode($request);
$this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";
// performs the HTTP POST
$ch = curl_init($this->url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response = json_decode(curl_exec($ch),true);
curl_close($ch);
这适合我。