How to use file_get_contents() and stream_context_create() Functions In PHP
This approach involves creating a stream context to configure the request and then using file_get_contents() function to perform the POST request. It is a basic method suitable for simple scenarios.
Example:
PHP
<?php // Define the URL and data $url = 'https://example.com/' ; $data = [ 'key' => 'value' ]; // Prepare POST data $options = [ 'http' => [ 'method' => 'POST' , 'header' => 'Content-type: application/x-www-form-urlencoded' , 'content' => http_build_query( $data ), ], ]; // Create stream context $context = stream_context_create( $options ); // Perform POST request $response = file_get_contents ( $url , false, $context ); // Display the response echo $response ; ?> |
Here, define the target URL and the data to be sent. Create a stream context with the appropriate POST headers and data. Use file_get_contents with the created context to perform the POST request. Display the received response.
Output:
How to send a POST Request with PHP ?
In web development, sending POST requests is a common practice for interacting with servers and exchanging data. PHP, a versatile server-side scripting language, provides various approaches to accomplish this task. This article will explore different methods to send POST requests using PHP.
Table of Content
- Using file_get_contents() and stream_context_create() Functions
- Leveraging the cURL Library
- Utilizing the HTTP_Request2 Class
Contact Us