Make POST requests with file_get_contents in PHP


You can pass URL into file_get_contents to download content with HTTP GET request:

$page = file_get_contents('');

However, you can do much more. You can make any type of HTTP requests, add custom request headers as well as request body. A complete example of HTTP POST request with file_get_contents:

$options =
    'http' =>
        'method'  => 'POST',
        'header'  => "Content-Type: application/x-www-form-urlencoded\n" .
                     "User-Agent: Badass Bot",
        'content' => http_build_query
            'name' => 'Sam',
            'age'  => 25

$context  = stream_context_create($options);
$result = file_get_contents('', false, $context);

You can replace method value with HEAD, PUT, DELETE, or any other type of HTTP request which you need to send.

Rate this post:
Share this page:

See also how to:

How to run your PHP or Bash script as root in the most secure way
How to use modern MaxMind GeoIP API in PHP
How to split YAML files and include them into each other with PHP
How to protect your website forms from unwanted spam bots
How to create a well-crafted RSS feed for a website and configure it property