PHP POST 请求示例:使用 file_get_contents 发送数据
以下是一个简单的 PHP POST 请求示例,展示如何使用 file_get_contents 函数发送数据到 API 接口:
$url = 'https://example.com/api'; // API 接口 URL
$data = array('username' => 'john', 'password' => '123456'); // POST 数据
$options = array(
'http' => array(
'header' => 'Content-type: application/x-www-form-urlencoded\r\n',
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
在上面的示例中,我们首先定义了 API 接口的 URL 和要发送的 POST 数据。然后,我们使用 PHP 的 file_get_contents 函数发送 POST 请求,并使用 stream_context_create 函数创建了一个包含 POST 数据的 HTTP 头和请求方法的选项数组。最后,我们将返回的响应输出到屏幕上。
原文地址: https://www.cveoy.top/t/topic/mqyh 著作权归作者所有。请勿转载和采集!