php 发送header
时间: 2023-08-28 21:03:40 浏览: 42
PHP 发送 header 可以使用 `header()` 函数。该函数用于向客户端发送一个原始的 HTTP 报头。
以下是使用 PHP 发送 HTTP 响应头的示例:
```php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
echo json_encode(array('message' => 'Hello World!'));
```
上述示例中,第一行设置了响应的 Content-Type 为 application/json,第二行设置了跨域访问的允许来源为 *(所有来源),第三行设置了该 API 允许的 HTTP 请求方法为 GET 和 POST。最后一行输出了一个 JSON 对象。
请注意,`header()` 函数必须在任何实际输出之前调用。如果在输出之后调用,则会发生错误。
相关问题
php 设置http请求header
在 PHP 中,可以使用 `header()` 函数来设置 HTTP 请求头。该函数需要在发送任何实际输出之前调用,并且只能调用一次。
以下是设置 HTTP 请求头的示例代码:
```
<?php
header("Content-Type: application/json");
header("Authorization: Bearer abcdef1234567890");
?>
```
在上面的示例中,`Content-Type` 和 `Authorization` 是两个常见的 HTTP 请求头。第一个头告诉客户端返回的内容类型是 JSON,而第二个头是一个身份验证令牌。
可以在 `header()` 函数中添加任意数量的头,每个头都必须用一个单独的 `header()` 函数调用。请注意,如果在启用输出缓冲区时调用 `header()` 函数,则必须先调用 `ob_start()` 函数。
php发送json示例
以下是一个 PHP 发送 JSON 的示例:
```php
$data = array(
'name' => 'John Doe',
'email' => 'johndoe@example.com',
'phone' => '123-456-7890'
);
$json = json_encode($data);
$url = 'https://example.com/api';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
```
这个示例中,我们首先创建了一个包含一些数据的数组,然后使用 `json_encode()` 函数将其转换为 JSON 格式。接下来,我们设置了一个 URL,然后使用 cURL 发送 POST 请求,将 JSON 数据作为请求体发送。我们还设置了一个 `Content-Type` 头部,告诉服务器我们发送的是 JSON 数据。最后,我们使用 `curl_exec()` 函数执行请求,并输出服务器的响应。