Sources


file_get_contents() is an amazing flexible function, although probably quite controversial depending on its use. Initialy file_get_contents() is used to read out data in a file, but this function has some additional quirks that it can be used for aswell. For example pass it a URL instead and it will read out the html content of a page. Pass it a route to your API and it will read the response as if it were making a GET request.

In addition, it can also be configured to make POST requests. This is the tricky part as I would not recommend using this ever unless its for some tiny pet project hack you would like to wip together (and I have done it so I'm just as guilty). A better practice would be to use PHP's built in cURL library or my personal preference, the Httpful Library. But lets take a look at this "hack". Below is an example:

$body["data"]["username"] = "bensoer";
$body["data"]["firstname"] = "ben";
$body["data"]["lastname"] = "soer";
$body["data"]["password"] = "supersecret";
$json_data = json_encode($body);

$post = file_get_contents("http://api.somewebsite.com/api/user,null,
    stream_context_create(array(
        'http' => array(
            'protocol_version' => 1.1,
            'user_agent'       => 'phpExample',
            'method'           => 'POST',
            'header'           => "Content-type: application/json\r\n".
                "Connection: close\r\n" .
                "Content-length: " . strlen($json_data) . "\r\n",
            'content'          => $json_data,
        ),
    ))
);
if($post){  
    //request was successful
}else{
    //request failed
}

From the first few lines you can see were creating our json body content for our post request. Then we get to our file_get_contents()call. First parameter is the URL, second parameter sets whether to use the php include path in searching / resolving the first parameter. Obviously this would be more applicable if you were reading out a text file, therefor null is passed for now. If you were reading a file you can use the FILE_USE_INCLUDE_PATH constant for this parameter. The third parameter is the context parameter, and this can be used in many ways to manipulate how the file_get_contents() works. By using a stream_context_create object we can essentially rewrite the functionality of file_get_contents() to act like a POST request client. As you can see in the example, we changed it to http 1.1, set it to method POST, set its content type for json so we can pass json as body content and then appended our body data to the request. The function then returns a value, FALSE is returned on failure, and other values are returned if it is successful. What it actually returns I have not tried out myself yet. I never needed what it returned when i used it, just that it succeeded