jrobinsonc
6/26/2017 - 5:53 PM

Send GET and POST requests with file_get_contents.

Send GET and POST requests with file_get_contents.

<?php

function sendRequest($method, $url, $content = '', $headers = []) {
    $opts = [
        'http' => [
            'method'  => $method,
            'header'  => implode("\r\n", $headers),
            'content' => $content
        ]
    ];

    return file_get_contents($url, false, stream_context_create($opts));
}


// Usage 
$data = [
    'param1' => 'value1',
    'param2' => 'value2'
];

$headers = [
    'Content-Type: application/x-www-form-urlencoded'
];

sendRequest('POST', 'https://requestb.in/xyz123', http_build_query($data), $headers);