How do I send a POST request with PHP? How do I send a POST request with PHP? php php

How do I send a POST request with PHP?


CURL-less method with PHP5:

$url = 'http://server.com/path';$data = array('key1' => 'value1', 'key2' => 'value2');// use key 'http' even if you send the request to https://...$options = array(    'http' => array(        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",        'method'  => 'POST',        'content' => http_build_query($data)    ));$context  = stream_context_create($options);$result = file_get_contents($url, false, $context);if ($result === FALSE) { /* Handle error */ }var_dump($result);

See the PHP manual for more information on the method and how to add headers, for example:


You could use cURL:

<?php//The url you wish to send the POST request to$url = $file_name;//The data you want to send via POST$fields = [    '__VIEWSTATE '      => $state,    '__EVENTVALIDATION' => $valid,    'btnSubmit'         => 'Submit'];//url-ify the data for the POST$fields_string = http_build_query($fields);//open connection$ch = curl_init();//set the url, number of POST vars, POST datacurl_setopt($ch,CURLOPT_URL, $url);curl_setopt($ch,CURLOPT_POST, true);curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);//So that curl_exec returns the contents of the cURL; rather than echoing itcurl_setopt($ch,CURLOPT_RETURNTRANSFER, true); //execute post$result = curl_exec($ch);echo $result;?>


I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

function httpPost($url, $data){    $curl = curl_init($url);    curl_setopt($curl, CURLOPT_POST, true);    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);    $response = curl_exec($curl);    curl_close($curl);    return $response;}

@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().