Search code snippets, questions, articles... Chrome Extension

Send POST request without using curl using PHP 5+

If you are using a PHP version higher than 5, then you can easily send a post request without using curl. The code to send post requests in PHP is as below.
<?php
    $api_url = 'https://domain.com/endpoint';
    $post_data = [
        'name' => 'Rick', 
        'city' => 'Atlanta'
    ];

    // We are using 'http' key 
    $request_options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded
",
            'method'  => 'POST',
            'content' => http_build_query($post_data)
        ]
    ];
    $stream_context  = stream_context_create($request_options);
    $response = file_get_contents($api_url, false, $stream_context);
    if ($response === FALSE) {
        // Code to handle error here
    }

    var_dump($response);
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

In the above code snippet, we are sending a POST request with post data. PHP variable $request_options contains options to be sent in the request. We are using key 'http' here and assigning out headers, type of method and content to it. Even if you are sending the request to https, the name should remain http.

After making options we are passing them to the stream_context_create() method of PHP that will crate the stream context. Finally, the stream context is passed to the file_get_contents() method along with API_URL. This will return the response from the API that we assigned to the $response variable here.

If the $response variable is false then an error is returned from POST API and we can handle that.

Was this helpful?
0 Comments
Join Devsheet Ask a Question