PHP

php http请求如何设置请求头

小樊
122
2024-07-05 03:15:24
栏目: 编程语言

在PHP中,可以使用stream_context_create()函数来创建一个HTTP请求的上下文,并使用stream_context_set_option()函数来设置请求头。

以下是一个示例:

<?php
$url = 'http://example.com/api';
$headers = array(
    'Content-Type: application/json',
    'Authorization: Bearer token'
);

$options = array(
    'http' => array(
        'header' => $headers
    )
);

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

echo $response;
?>

在上面的例子中,我们首先定义了请求的URL和请求头。然后创建一个$options数组,包含了HTTP请求的头部信息。最后使用stream_context_create()函数创建请求上下文,并将其传递给file_get_contents()函数来发送HTTP请求。

通过这种方式,我们可以设置HTTP请求头部信息,并发送HTTP请求。

0
看了该问题的人还看了