php怎么發(fā)送post請(qǐng)求

PHP
小億
91
2024-02-23 13:53:28

在PHP中發(fā)送POST請(qǐng)求可以使用curl或者file_get_contents函數(shù)。

使用curl發(fā)送POST請(qǐng)求的示例代碼如下:

$url = 'http://example.com/post_endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if(curl_errno($ch)){
    echo 'Curl error: ' . curl_error($ch);
}

curl_close($ch);

echo $response;

使用file_get_contents發(fā)送POST請(qǐng)求的示例代碼如下:

$url = 'http://example.com/post_endpoint';
$data = array('key1' => 'value1', 'key2' => 'value2');

$options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => http_build_query($data)
    )
);

$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

echo $response;

以上代碼示例中,$url變量是目標(biāo)URL地址,$data變量是POST請(qǐng)求的數(shù)據(jù)。使用curl函數(shù)或file_get_contents函數(shù)將數(shù)據(jù)發(fā)送到目標(biāo)URL,并獲取到返回的數(shù)據(jù)。

0