How to set header in curl in PHP?

Guanhui
Release: 2023-03-02 22:04:02
Original
12114 people have browsed it

How to set header in curl in PHP?

How to set header in curl in PHP?

In the PHP extension library curl, you can set the option constant "CURLOPT_HTTPHEADER" through the function "curl_setopt()" to set the header. When using it, just pass the header data into the third parameter.

<?php

$header  = array(
  &#39;x-api-key:&#39;.&#39;b8602c0361111415a221759cdeb9e636&#39;,
  &#39;Content-Type:&#39;.&#39;application/x-www-form-urlencoded; charset=UTF-8&#39;
);

/**
 * @param $url
 * @param null $data
 * @return bool|string
 */
public function http_request($url, $data = null, $header = null){
 
    $curl = curl_init();
    if(!empty($header)){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
    }
 
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,http_build_query($data));
    }
 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
Copy after login

Recommended tutorial: "PHP"

The above is the detailed content of How to set header in curl in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template