Home Backend Development PHP Tutorial PHP uses stream_context_create() to simulate POST/GET request method and example analysis

PHP uses stream_context_create() to simulate POST/GET request method and example analysis

Jun 04, 2018 am 10:35 AM
context create stream

This article mainly introduces the method of PHP using stream_context_create() to simulate POST/GET requests. It analyzes the principle of stream_context_create to simulate POST/GET requests in detail in the form of examples, the usage method and related precautions. Friends in need can Refer to the next

Sometimes, we need to simulate POST/GET and other requests on the server side, that is, to implement the simulation in the PHP program. How to do it? In other words, in a PHP program, if you are given an array, how do you POST/GET this array to another address? Of course, it's easy to do it using CURL, but what if you don't use the CURL library? In fact, there is already a related function implemented in PHP, and this function is stream_context_create() that I will talk about next.

Show you the code directly, this is the best way:


$data = array(
    'foo'=>'bar', 
    'baz'=>'boom', 
    'site'=>'localhost', 
    'name'=>'nowa magic'); 
$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 * 60 // 超时时间(单位:s)
    )
);
$url = "http://localhost/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
Copy after login


http:/ The code of /localhost/test2.php is:


$data = $_POST;
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r( $data );
echo &#39;
';
Copy after login


The running result is:


Array
(
  [foo] => bar
  [baz] => boom
  [site] => localhost
  [name] => nowa magic
)
Copy after login


Some key points to explain:

1. The above program uses the http_build_query() function. If you need to know more, you can refer to the previous article "PHP uses http_build_query()" Method to construct URL string》.

2. stream_context_create() is used to create context options for opening files, such as accessing with POST, using a proxy, sending headers, etc. Just create a stream. Let’s give another example:


$context = stream_context_create(array( 
    &#39;http&#39; => array( 
        &#39;method&#39; => &#39;POST&#39;, 
        &#39;header&#39; => sprintf("Authorization: Basic %s\r\n", base64_encode($username.&#39;:&#39;.$password)). 
        "Content-type: application/x-www-form-urlencoded\r\n", 
        &#39;content&#39; => http_build_query(array(&#39;status&#39; => $message)), 
        &#39;timeout&#39; => 5, 
    ), 
)); 
$ret = file_get_contents(&#39;http://twitter.com/statuses/update.xml&#39;, false, $context);
Copy after login


##3. The context options created by stream_context_create can be used for streams. , can also be used in file systems. It is more useful for functions like file_get_contents, file_put_contents, and readfile that operate directly on file names without file handles. Adding headers to stream_context_create is only part of the function. You can also define proxies, timeouts, etc. This makes the function of accessing the web not weaker than curl.

4. The function of stream_context_create(): Create and return a text data stream and apply various options, which can be used for timeout settings, proxy servers, request methods, and header information settings of fopen(), file_get_contents() and other processes. special process.

5. stream_context_create can also solve file_get_contents timeout processing by adding the timeout option:

##

$opts = array(
  &#39;http&#39;=>array(
  &#39;method&#39;=>"GET",
  &#39;timeout&#39;=>60,
 )
);
//创建数据流上下文
$context = stream_context_create($opts);
$html =file_get_contents(&#39;http://localhost&#39;, false, $context);
//fopen输出文件指针处的所有剩余数据:
//fpassthru($fp); //fclose()前使用
Copy after login

Summary: The above is the entire content of this article, I hope it can help Everyone’s learning helps.

Related recommendations:

phpQuick sorting principle, implementation method and example analysis

PHPExcel Methods and simple examples to implement reading excel files


##PHP MVC framework skymvc supports multiple file upload implementation methods


The above is the detailed content of PHP uses stream_context_create() to simulate POST/GET request method and example analysis. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does context mean? What does context mean? Aug 04, 2023 pm 05:27 PM

Context is the environment and status information when the program is executed. It can include a variety of information, such as the value of variables, the call stack of functions, the execution location of the program, etc., allowing the program to make corresponding decisions based on different contexts. and perform corresponding operations.

How to debug Java Stream operations in IntelliJ IDEA How to debug Java Stream operations in IntelliJ IDEA May 09, 2023 am 11:25 AM

Stream operation is a highlight of Java8! Although java.util.stream is very powerful, there are still many developers who rarely use it in actual work. One of the most complained reasons is that it is difficult to debug. This was indeed the case at the beginning, because streaming operations such as stream cannot be used in DEBUG When it is one line of code, when it comes to the next step, many operations are actually passed at once, so it is difficult for us to judge which line in it is the problem. Plug-in: JavaStreamDebugger If the IDEA version you are using is relatively new, this plug-in is already included and does not need to be installed. If it is not installed yet, install it manually and then continue below.

How to use context to implement request caching in Go How to use context to implement request caching in Go Jul 22, 2023 pm 10:51 PM

How to use context to implement request caching in Go Introduction: When building web applications, we often need to cache requests to improve performance. In the Go language, we can use the context package to implement the request caching function. This article will introduce how to use the context package to implement request caching, and provide code examples to help readers better understand. What is context? : In the Go language, the context package provides a way to pass between multiple goroutines

How to use context to implement request link tracking in Go How to use context to implement request link tracking in Go Jul 21, 2023 pm 05:57 PM

How to use context to implement request link tracking in Go. In the microservice architecture, request link tracking is a very important technology that is used to track the delivery and processing of a request between multiple microservices. In the Go language, we can use the context package to implement request link tracking. This article will introduce how to use context for request link tracking and give code examples. First, we need to understand the basic concepts and usage of the context package. The context package provides a mechanism

How to get max value from stream in java8 How to get max value from stream in java8 May 14, 2023 pm 03:43 PM

java8's stream takes maxpublicstaticvoidmain(String[]args){Listlist=Arrays.asList(1,2,3,4,5,6);Integermax=list.stream().max((a,b)->{if (a>b){return1;}elsereturn-1;}).get();System.out.println(max);}Note: The size is determined here through positive and negative numbers and 0 values. Instead of writing it directly if(a>b){returna;}elseretur

How to use context to implement request timeout control in Go How to use context to implement request timeout control in Go Jul 21, 2023 pm 12:18 PM

How to use context to implement request timeout control in Go Introduction: When we make network requests, we often encounter request timeout problems. A network request that does not respond for a long time will not only waste server resources, but also affect overall performance. In order to solve this problem, the Go language introduced the context package, which can be used to implement request timeout control. This article will introduce how to use the context package to implement request timeout control in Go, and attach corresponding code examples. 1. Understand the context package co

How to use context to implement request retry strategy in Go How to use context to implement request retry strategy in Go Jul 21, 2023 pm 04:39 PM

How to use context to implement request retry strategy in Go Introduction: When building a distributed system, network requests will inevitably encounter some failures. In order to ensure the reliability and stability of the system, we usually use a retry strategy to handle these failed requests to increase the success rate of the request. In the Go language, we can use the context package to implement the request retry strategy. This article will introduce how to use the context package in Go to implement a request retry strategy, with code examples. 1. What is

What does stream mean in linux? What does stream mean in linux? Mar 17, 2023 am 09:55 AM

In Linux, stream means data flow, which is a string of data read in a certain order, so the direction of the data flow is the reading order of the data flow. The process of the Linux system importing the output results after reading the data into other files is called redirected data flow. After a command is entered and run under Linux, two results will be displayed on the screen: the result of a successful operation is the standard output, and the result of a failed operation is the standard error output; if not processed, they will be displayed on the screen and redirected through the data stream. You can save it to other files.

See all articles