PHP Simple example of sending http requests using file_get_contents

  • 2021-09-20 19:47:46
  • OfStack

This article exemplifies the PHP's ability to send http requests using file_get_contents. Share it for your reference, as follows:

Server-side simulation of POST/GET and other requests is easy to do by using CURL (for example, the previous article "php uses CURL to simulate the method of submitting and obtaining data from GET and POST to WeChat interface"), so what should I do if I don't use CURL library?


$data = array(
  'test'=>'bar',
  'baz'=>'boom',
  'site'=>'www.nimip.com',
  'name'=>'nimip.com');
$data = http_build_query($data);
//$postdata = http_build_query($data);
$options = array(
  'http' => array(
    'method' => 'POST',
    'header' => 'Content-type:application/x-www-form-urlencoded',
    'content' => $data
    'timeout' => 60 //  Time-out (unit :s ) 
  )
);
$url = "http://www.testweb.com";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;

The code of http://www.testweb.com is:


$data = $_POST;
print_r( $data );

stream_context_create() Function: Create and return a text data stream and apply various options, which can be used for fopen() , file_get_contents() Such as the process of timeout settings, proxy server, request mode, header information settings of the special process.

For more readers interested in PHP related content, please check the topics on this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Operation and Operator Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: