PHP Curl POST Request with Headers Example

By Hardik Savani May 14, 2024 Category : PHP

Hi,

This post will give you example of php curl post request with headers example. In this article, we will implement a how to send headers in curl php. i explained simply step by step how to send headers in php curl. we will help you to give example of php curl post request header. Here, Creating a basic example of php curl post data header.

PHP cURL have set of curl function like curl_init(), curl_setopt(), curl_exec() etc. using cURL we will call post api with headers to getting json data and we can use their data in our project.

Here, i will give you very simple example of curl post request with headers with authentication example on bellow of simple curl request example:

Simple Example:

<?php

/* API URL */

$url = 'http://www.mysite.com/api';

/* Init cURL resource */

$ch = curl_init($url);

/* Array Parameter Data */

$data = ['name'=>'Hardik', 'email'=>'itsolutionstuff@gmail.com'];

/* pass encoded JSON string to the POST fields */

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

/* set the content type json */

$headers = [];

$headers[] = 'Content-Type:application/json';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

/* set return type json */

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

/* execute request */

$result = curl_exec($ch);

/* close cURL resource */

curl_close($ch);

>

Header Auth Example:

<?php

/* API URL */

$url = 'http://www.mysite.com/api';

/* Init cURL resource */

$ch = curl_init($url);

/* Array Parameter Data */

$data = ['name'=>'Hardik', 'email'=>'itsolutionstuff@gmail.com'];

/* pass encoded JSON string to the POST fields */

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

/* set the content type json */

$headers = [

'Content-Type:application/json',

'App-Key: 123456',

'App-Secret: 1233'];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

/* set return type json */

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

/* execute request */

$result = curl_exec($ch);

/* close cURL resource */

curl_close($ch);

>

Now you can check it

I hope it can help you...

Tags :
Shares