


PHP simulates sending POST requests 4, strengthen file_get_contents() to send POST requests, filepostcontents_PHP tutorial
PHP simulates sending POST requests four, strengthen file_get_contents() to send POST requests, filepostcontents
After using the cumbersome fsockopen() method, we started looking for more information in the PHP function library A simple way to make a POST request. At this time, we discovered that PHP's file function also has the function of interacting with remote URLs.
The simplest ones are the fopen() and fread() functions.
<span>$fp</span>=<span>fopen</span>('http://localhost?query=query','r'<span>); </span><span>$content</span>=<span>fread</span>(<span>$fp</span>,1024<span>); </span><span>echo</span> <span>$content</span>;<span>//</span><span>输出HTML文档信息</span> <span>fclose</span>(<span>$fp</span>);
Then the file_get_contents() function:
<span>$content</span>=<span>file_get_contents</span>('http://localhost?query=query'<span>); </span><span>echo</span> <span>$content</span>;<span>//</span><span>输出HTML文档信息</span>
However, we will find that through these two methods, we can only send information and read web page information through GET. Moreover, these two methods also face problems such as timeout and inability to process header information.
However, let’s take a closer look at the function prototype of file_get_contents():
<p>string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )</p>
We found that it has other optional parameters. By setting these parameters, we can POST out our data while sending the web page request. The meaning of each parameter is explained below.
- $filename: Needless to say, just fill in the URL string we want to access.
- $use_include_path: Whether to use the path set by include_path() before the file. If used, when the file address is not found, it will automatically go to the path set by include_path() to find it. In the web address, we set it to false.
- $context: Environmental context, resource type, set by the context returned by the function stream_context_create(), which is also the focus of our file_get_contents() function expansion. Let’s talk about it next.
- $offset: The offset byte of the read content relative to the beginning of the file. When we read web page content, we must ensure the integrity of the HTML document, so it can be set to 0 or not set. The default is 0.
- $maxlen: As the name suggests, it is the maximum number of bytes to read the file. We do not set the same offset and read the entire content of the web page.
The focus of sending a POST request through file_get_contents is the $context parameter. We use the stream_context_create() function to set the context.
The context options created by stream_context_create() can be used for both streams and 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.
Let’s look at the prototype of the stream_context_create() function:
<p>resource stream_context_create ([ array $options [, array $params ]] )</p>
We see that this function is used to obtain the context options of a resource type by passing in the settings array.
<span>$context</span> = <span>stream_context_create</span>(<span>array</span>( <span>//</span><span>传入数组类型的$option参数</span> 'http' => <span>array</span>( <span>//</span><span>以HTTP请求为键的设置数组</span> 'method' => 'POST', <span>//</span><span>设置请求方法为POST</span> 'header' => "Content-type: application/x-www-form-urlencoded",<span>//</span><span>通过设置头文件来设置POST数据格式</span> 'content' => <span>http_build_query</span>(<span>$query_info</span>), <span>//</span><span>用http_build_query()方法将数组拼合成数据字符串</span> 'timeout' => 20 <span>//</span><span>设置请求的超时时间。</span> <span> ) )); </span>
After setting the context, we submit POST data through the file_get_contents() function.
<span>$results</span> = <span>file_get_contents</span>('http://localhost', <span>false</span>, <span>$context</span>);
Here is a complete example of a POST request:
<span>$info</span>=['eat'=>'2kg','run'=>'10km'<span>] ; </span><span>$url</span>='http://localhost'<span>; </span><span>$context</span> = <span>stream_context_create</span>(<span>array</span><span>( </span>'http' => <span>array</span><span>( </span>'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => html_build_query(<span>$info</span>), 'timeout' => 20<span> ) )); </span><span>$result</span> = <span>file_get_contents</span>(<span>$url</span>, <span>false</span>, <span>$context</span>);
If you think this article is helpful to you, you can recommend it or follow me. In addition, if you have any questions, you can leave a message below for discussion. Thank you.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
