2014-09-25 41 views
0

我有三个Web服务器。其中两个论坛有一个需要在发送发布请求时运行的php脚本,第三个脚本发送命令给两个较低的服务器。我需要发送一个post请求到2个较低的服务器,只使用php。这是我当前的代码:仅在服务器间发送帖子php

所有的
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

停止使用'@'来抑制您的错误消息。抑制错误的函数可能是问题,并且你压制的错误会告诉你为什么。 – Sammitch 2014-09-25 16:26:59

+0

我的错误实际上在于代码中的其他地方,但下面的curl方法比我目前的更好。 – Aurora 2014-09-25 16:37:34

回答

0

你应该使用卷曲

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

卷曲是你所需要的:

例如,我需要把一些变量将消息发送文本电话:

<?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而不是回显。