search
HomeBackend DevelopmentPHP TutorialPHP implements post and get

file_get_contents版本:

01 <?php

02 /**

03 * Send post request

04 * @param string $url request address

05 * @param array $post_data post key-value pair data

06 * @return string

07 */

08 functionsend_post($url, $post_data) {

09  

10     $postdata= http_build_query($post_data);

11     $options= array(

12         'http'=> array(

13             'method'=> 'POST',

14             'header'=> 'Content-type:application/x-www-form-urlencoded',

15             'content'=> $postdata,

16             'timeout'=> 15 * 60 // 超时时间(单位:s)

17         )

18     );

19     $context= stream_context_create($options);

20     $result= file_get_contents($url, false, $context);

21  

22     return$result;

23 }

使用如下:

1 $post_data= array(

2     'username'=> 'stclair2201',

3     'password'=> 'handan'

4 );

5 send_post('http://blog.snsgou.com', $post_data);

Practical experience:

When I used the above code to send an http request to another server, I found that if the server takes too long to process the request, the local PHP will interrupt the request, which is the so-called timeout interrupt. The first one I suspect that the execution time of PHP itself exceeds the limit, but I shouldn’t think about it because I have set the “PHP execution time limit” according to this article a long time ago ([Recommended] PHP upload file size limit list). After careful consideration, I thought I thought it should be a time limit on the http request itself, so I thought of how to increase the time limit on the http request. . . . . . Check the PHP manual, and there is indeed a parameter "timeout", I don't know how big it is by default. When you set its value to a larger value, the problem will be solved. Let me make a note~~~

Socket version:

01 /**

02 * Socket version

03 * How to use:

04 * $post_string = "app=socket&version=beta";

05 * request_by_socket( 'blog.snsgou.com', '/restServer.php', $post_string);

06 */

07 functionrequest_by_socket($remote_server ,$remote_path,$ post_string,$port= 80,$timeout= 30) {

08 $socket= fsockopen ($remote_server, $port, $errno, $errstr, $timeout);

09 if(!$socket) die("$errstr($errno)");

10 fwrite($socket, "POST $remote_path HTTP/1.0");

11, 12
$socket "User-Agent: Socket Example");

et, );
"HOST: $remote_server" 13
fwrite(

$sock et, ); $post_string) + 8) .
"Content-type: application/x-www-form-urlencoded" $socket, "Content-length: ". (strlen(
""

);16
15 "Accept:*/*");
)

fwrite($socket ""17
, );

"mypost=$post_string");fwrite($socket
18
,

"");$header=
19
""

;

20     while($str= trim(fgets($socket, 4096))) {

21         $header.= $str;

22     }

23  

24     $data= "";

25     while(!feof($socket)) {

26         $data.= fgets($socket, 4096);

27     }

28  

29     return$data;

30 }

Curl版本:

01 /**

02  * Curl版本

03  * 使用方法:

04  * $post_string = "app=request&version=beta";

05  * request_by_curl('http://blog.snsgou.com/restServer.php', $post_string);

06  */

07 functionrequest_by_curl($remote_server, $post_string) {

08     $ch= curl_init();

09     curl_setopt($ch, CURLOPT_URL, $remote_server);

10     curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost='. $post_string);

11     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

12     curl_setopt($ch, CURLOPT_USERAGENT, "snsgou.com's CURL Example beta");

13     $data= curl_exec($ch);

14     curl_close($ch);

15  

16     return$data;

17 }

Curl版本(2)

01 /**

02  * 发送HTTP请求

03 *

04 * @param string $url request address

* @param string $refererUrl request source address
05 * @param string $method Request method GET/POST

* @param array $data Send data
07

* @param string $contentType
08

* @param string $timeout
09

* @param string $proxy
10

* @return boolean
11

*/
12

send_request(
13function
$url

,

$data​ $ch
, $refererUrl = '', $method= 'GET', $contentType= 'application/json', $timeout= 30, $proxy= false) {14
= null;

if
15​​
(

'POST'

===
strtoupper( $method )) { 16                                                                                                                                                                 
17

                                                                             $ch
, CURLOPT_POST, 1); 18
, CURLOPT_HEADER,0 );

, CURLOPT_RETURNTRANSFER, 1);
~ 20                                                                    ch

21
$ch, CURLOPT_FORBID_REUSE, 1);

22                                                                                                                                                                curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

23 $refererUrl) {

24
                                                                                                                                     $refererUrl);

25

) {
26 ($contentType

27             curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:'.$contentType));

28         }

29         if(is_string($data)){

30             curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

31         } else{

32             curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

33         }

34     } elseif('GET'=== strtoupper($method)) {

35         if(is_string($data)) {

36             $real_url= $url. (strpos($url, '?') === false ? '?': ''). $data;

37         } else{

38             $real_url= $url. (strpos($url, '?') === false ? '?': ''). http_build_query($data);

39         }

40  

41         $ch= curl_init($real_url);

42         curl_setopt($ch, CURLOPT_HEADER, 0);

43         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:'.$contentType));

44         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

45         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

46         if($refererUrl) {

47             curl_setopt($ch, CURLOPT_REFERER, $refererUrl);

48         }

49     } else{

50         $args= func_get_args();

51         returnfalse;

52     }

53  

54     if($proxy) {

55         curl_setopt($ch, CURLOPT_PROXY, $proxy);

56     }

57     $ret= curl_exec($ch);

58     $info= curl_getinfo($ch);

59     $contents= array(

60             'httpInfo'=> array(

61                     'send'=> $data,

62                     'url'=> $url,

63                     'ret'=> $ret,

64                     'http'=> $info,

65             )

66     );

67  

68     curl_close($ch);

69     return$ret;

70 }

调用 WCF接口 的一个例子:$json = restRequest($r_url,'POST', json_encode($data));

以上就介绍了php实现post和get,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.