How to send a post request through header() with php?

by darrion.kuhn , in category: PHP General , a year ago

How to send a post request through header() with php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year ago

@darrion.kuhn 

To send a POST request using the header() function in PHP, you need to set the HTTP headers appropriately. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
$url = 'http://example.com/api'; // Replace with your target URL

// Set POST data
$data = array(
    'param1' => 'value1',
    'param2' => 'value2'
);

// Convert data array to a query string
$data = http_build_query($data);

// Set headers
$headers = array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: ' . strlen($data)
);

// Create a context
$context = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => implode("
", $headers),
        'content' => $data
    )
);

// Send the HTTP request
$result = file_get_contents($url, false, stream_context_create($context));

// Handle the response
echo $result;
?>


In this example, the code sends a POST request to http://example.com/api and includes two parameters: param1 with a value of value1 and param2 with a value of value2. The response from the server is then printed.


Make sure to replace 'http://example.com/api' with the actual URL you want to send the POST request to, and modify the data array to include the desired parameters and values.