PHP发送和接收POST数据

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."\r\n", FILE_APPEND);
}

$arr = array(  
    'code' => 0,  
    'errMsg' => 'OK',  
    // 'member' =>array(  
        // array(  
            // 'name' => '李逍遥',  
            // 'gender' => '男'  
        // ),  
        // array(  
            // 'name' => '赵灵儿',  
            // 'gender' => '女'  
        // )  
    // )  
);  
  
echo json_encode($arr);  
?>
复制代码
转自:http://www.cnblogs.com/txw1958/p/php-post.html
posted @ 2016-09-07 12:23  __Rain丶  阅读(15261)  评论(0编辑  收藏