我有三个网络服务器。其中两个有一个php的snippit需要在发送post请求时运行,而第三个用于向两个较低的服务器发送命令。我需要使用php向2个下层服务器发送一个帖子请求。这是我目前的代码:
function sendcom($sData, $sUrl){
$params = array('http' => array(
'method' => 'POST',
'content' => $sData
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp) {
Exit;
}
$response = @stream_get_contents($fp);
if ($response === false) {
Exit;
}
}
?>
首先,为什么在将数据发送到子级服务器时此脚本不起作用。第二,有没有更好的方法来做到这一点(记住,我只使用PHP)。
答案 0 :(得分:0)
你应该使用CURL
function sendcom($sData, $sUrl){
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $sUrl);
curl_setopt($ch,CURLOPT_POSTFIELDS, $sData);
//execute post
curl_exec($ch);
// Check Error
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
} else {
echo "<h2>Posted</h2>";
}
curl_close($ch);
}
答案 1 :(得分:0)
Curl就是你所需要的:
例如,我需要发送一些变量来发送消息文本到手机:
<?php
$phoneNumber = '4045551111';
$message = 'This message was generated by curl and php';
$curlPost = 'pNUMBER=' . urlencode($phoneNumber) . '&MESSAGE=' . urlencode($message) . '&SUBMIT=Send';
// initialize connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.webserver.com/sendSMS.php');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
//execute post
$data = curl_exec();
curl_close($ch);
或者您可以使用正确格式化的JSON数据通过JSON发送数据:
<?php
$data = array("phoneNumber" => "4045551111", "message" => "This message was generated by curl and php");
$data_string = json_encode($data);
// initialize connection
$ch = curl_init('http://www.webserver.com/sendSMS.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
//execute post
$result = curl_exec($ch);
curl_close($ch);
CURLOPT_RETURNTRANSFER
纯粹是为了让远程服务器的响应放在$result
而不是回显。