Home > Backend Development > PHP Tutorial > How Can I Send HTTP POST Data Using PHP's `file_get_contents()`?

How Can I Send HTTP POST Data Using PHP's `file_get_contents()`?

DDD
Release: 2024-12-20 11:57:09
Original
753 people have browsed it

How Can I Send HTTP POST Data Using PHP's `file_get_contents()`?

HTTP POST Data Transmission using PHP's file_get_contents()

When attempting to fetch URL content using PHP's file_get_contents() function, specific URLs may necessitate data posting. To fulfill this need, one can utilize the stream_context parameter.

To construct the necessary stream context, employ the following steps:

  1. Initialize Data: Define an array containing key-value pairs of data to post (e.g., ['var1' => 'some content']).
  2. Assemble Parameters: Create an array with 'http' as a key, containing an array of options including 'method' (set to 'POST'), 'header' (specifying Content-Type), and 'content' (populated with the data array).
  3. Establish Stream Context: Call stream_context_create() with the parameters array as an argument to generate the stream context.
  4. Execute POST Request: Invoke file_get_contents() with the target URL, providing the stream context as the third argument. This initiates the HTTP POST request and retrieves the response.

Example Code:

$postData = http_build_query([
    'var1' => 'some content',
    'var2' => 'doh'
]);

$opts = ['http' =>
    ['method' => 'POST',
    'header' => 'Content-Type: application/x-www-form-urlencoded',
    'content' => $postData]
];

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);
Copy after login

By implementing these steps, you can effectively submit HTTP POST data using file_get_contents(). While curl offers more capabilities, PHP's streams provide a less well-known but equally powerful alternative for HTTP POST operations.

The above is the detailed content of How Can I Send HTTP POST Data Using PHP's `file_get_contents()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template