PHP傳送和接收POST資料

方倍工作室發表於2016-08-24

1. 傳送post資料

$data = `{
    "id": "17999030",
    "method": "sayHello",
    "jsonrpc": "2.0",
    "params": 
        {
            "acmac": "00E0614CA7C6",
            "acconf_version": "2015-10-28-09-45"
        }
    }`;
$url = "http://wifi.doucube.com/index.php/interface/device/ConfHeartbeat.html";

$res = http_request($url, $data);

var_dump($res);

//HTTP請求(支援HTTP/HTTPS,支援GET/POST)
function http_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

 

2. 接收post資料

<?php
header(`Content-type: application/json`);

//方倍工作室
$postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"])?$GLOBALS["HTTP_RAW_POST_DATA"]:"";
logger(`http://`.$_SERVER[`HTTP_HOST`].$_SERVER[`PHP_SELF`].(empty($_SERVER[`QUERY_STRING`])?"":("?".$_SERVER[`QUERY_STRING`])));
logger($postStr);

foreach ($_GET as $key=>$value)  
{
    logger("_GET: Key: $key; Value: $value");
}
foreach ($_POST as $key=>$value)  
{
    logger("_POST: Key: $key; Value: $value");
}


//日誌記錄
function logger($log_content)
{
    $max_size = 100000;
    $log_filename = "raw.log";
    if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
    file_put_contents($log_filename, date(`H:i:s`)." ".$log_content."
", FILE_APPEND);
}

$arr = array(  
    `code` => 0,  
    `errMsg` => `OK`,  
    // `member` =>array(  
        // array(  
            // `name` => `李逍遙`,  
            // `gender` => `男`  
        // ),  
        // array(  
            // `name` => `趙靈兒`,  
            // `gender` => `女`  
        // )  
    // )  
);  
  
echo json_encode($arr);  
?>

 


相關文章