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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.