2016-02-19 40 views
1

我目前正在測試將POST數據從網頁傳遞到另一個URL,並試圖解決如何通過POST腳本將值從一個頁面傳遞到URL,然後該URL將處理POST數據通過服務器端腳本。我正在使用以下CURL來啓動POST,其中xxxyyy.com/post_processor.php是處理腳本的URL。正在處理POST數據服務器端

<?php 

//set POST variables 
$url = 'http://xxxyyy.com/post_processor.php'; 
$fields = array(
    'lname' => 'smith', 
    'fname' => 'peter', 
); 

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } 
rtrim($fields_string, '&'); 

//open connection 
$ch = curl_init(); 

//set the url, number of POST vars, POST data 
curl_setopt($ch,CURLOPT_URL, $url); 
curl_setopt($ch,CURLOPT_POST, count($fields)); 
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); 

//execute post 
$result = curl_exec($ch); 

//close connection 
curl_close($ch); 

?> 

該帖子爲預期的數據但是我無法處理任何已張貼信息(我在http://requestb.in/12lfg7x1測試過)。

目前,在服務器端的處理腳本只包含if語句看到任何數據後是否已經收到,如果是寫入數據庫:

$entityBody = file_get_contents('php://input'); 

if (!empty($entityBody)) 
    { 
     // handle post data 

    global $wpdb; 

      $table_name = $wpdb->prefix . 'post_data_1'; 
      $wpdb->insert( 
      $table_name, 
      array( 
       'time' => current_time('mysql'), 
       'post_data_recieved' => 'ok', 
      ) 
     ); 

} 

這個組合目前不工作,即我加載的初始腳本,沒有任何反應數據張貼,但沒有數據存儲在遠程數據庫。但是,如果我使用表單將POST數據傳遞給腳本,這確實有效,但如果我不通過重定向傳遞發佈數據,則不起作用。任何人都可以告訴我我在這裏做錯了什麼?

感謝,

馬特

+0

你從哪裏得到'$ entityBody'? – RamRaider

+0

$ entityBody = file_get_contents('php:// input'); – user1419810

回答

0

這在本質上是一樣什麼最初發布和工作在返回值是否成功打印到屏幕上。

數據庫沒有被更新的事實讓我覺得可能db連接在post_processor.php腳本中不可用,所以post_processor.php有所有必需的包含文件以確保$wpdb可用?

<?php 
    $url = 'http://xxxyyy.com/post_processor.php'; 
    $url = 'https://localhost/target.php'; 


    $fields = array(
     'lname'  => 'smith', 
     'fname'  => 'peter' 
    ); 
    /* prepare the data for transmission as a urlencoded string */ 
    $data=http_build_query($fields); 



    $ch = curl_init(); 

    if(parse_url($url,PHP_URL_SCHEME)=='https'){ 
     /* my server runs https so I need these lines*/ 
     curl_setopt($ch, CURLOPT_CAINFO, realpath('c:/wwwroot/cacert.pem')); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    } 

    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: '.strlen($data))); 

    $result = curl_exec($ch); 
    $info = curl_getinfo($ch); 
    curl_close($ch); 

    print_r($result); 
?> 



<?php 

    $data=file_get_contents('php://input'); 
    print_r($data); 

    /* what would this show ? Object hopefully I guess */ 
    echo '$wpdb = '.gettype($wpdb); 
?> 

outputs: 
lname=smith&fname=peter