PHP 发送application/json POST请求
阅读原文时间:2023年07月08日阅读:2

PHP用CURL发送Content-type为application/json的POST请求方法

function json_post($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(!$data){  
        return 'data is null';  
    }  
    if(is\_array($data))  
    {  
        $data = json\_encode($data);  
    }  
    curl\_setopt($curl, CURLOPT\_POST, 1);  
    curl\_setopt($curl, CURLOPT\_POSTFIELDS, $data);  
    curl\_setopt($curl, CURLOPT\_HEADER, 0);  
    curl\_setopt($curl, CURLOPT\_HTTPHEADER,array(  
            'Content-Type: application/json; charset=utf-8',  
            'Content-Length:' . strlen($data),  
            'Cache-Control: no-cache',  
            'Pragma: no-cache'  
    ));  
    curl\_setopt($curl, CURLOPT\_RETURNTRANSFER, 1);  
    $res = curl\_exec($curl);  
    $errorno = curl\_errno($curl);  
    if ($errorno) {  
        return $errorno;  
    }  
    curl\_close($curl);  
    return $res;

}
  • PHP接受JSON POST

$data = json_decode(file_get_contents('php://input'), true);